Marshal C++ int array to C#

前端 未结 2 1300
北恋
北恋 2020-11-30 12:49

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         


        
相关标签:
2条回答
  • 2020-11-30 13:12
    [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);
    
    0 讨论(0)
  • 2020-11-30 13:29

    Just to add a tip to Alex F Answer : If you don't know the size of Array it's easy to get,define another dll_export to get the array size.

    0 讨论(0)
提交回复
热议问题