Marshal C++ int array to C#
I would like to marshal an array of ints from C++ to C#. I have an unmanaged C++ dll which contains:
DLL_EXPORT int* fnwrapper_intarr()
{
int* test = new int[3];
test[0] = 1;
test[1] = 2;
test[2] = 3;
return test;
}
with declaration in header extern "C" DLL_EXPORT int* fnwrapper_intarr();
I am then using pinvoke to marshal it into C#:
[DllImport("wrapper_demo_d.dll")]
[return: MarshalAs(UnmanagedType.SafeArray)]
public static extern int[] fnwrapper_intarr();
And I use the function like so:
int[] test = fnwrapper_intarr();
However, during program execution I get the following error: SafeArray cannot be marshaled to this array type because it has either nonzero lower bounds or more than one dimension.
What array type should I be using? Or is there a bettery way of marshalling arrays or vectors of integers?
Solution 1:
[DllImport("wrapper_demo_d.dll")] public static extern IntPtr fnwrapper_intarr(); IntPtr ptr = fnwrapper_intarr(); int[] result = new int[3]; Marshal.Copy(ptr, result, 0, 3);
You need also to write Release function in unmanaged Dll, which deletes pointer created by fnwrapper_intarr. This function must accept IntPtr as parameter.
DLL_EXPORT void fnwrapper_release(int* pArray) { delete[] pArray; } [DllImport("wrapper_demo_d.dll")] public static extern void fnwrapper_release(IntPtr ptr); IntPtr ptr = fnwrapper_intarr(); ... fnwrapper_release(ptr);