Marshal C++ int array to C#

[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);

Leave a Comment