Marshaling unmanaged char** to managed string[]

前端 未结 1 1976
感动是毒
感动是毒 2021-01-16 06:18

I have a C++ function in a DLL file (it is compiled with the Multi-Byte Character Set option):

_declspec(dllexport) void TestArray(char** OutBuff,int Count,i         


        
1条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-16 06:41

    So OutBuff is basically an array of pointers - so you need to create an IntPtr array whose elements are valid pointers - that is IntPtr values that point to valid memory. Like below:

    int count = 10;
    int maxLen = 25;
    IntPtr[] buffer = new IntPtr[count];
    
    for (int i = 0; i < count; i++)
        buffer[i] = Marshal.AllocHGlobal(maxLen);
    
    TestArray(buffer, count, maxLen);
    
    string[] output = new string[count];
    for (int i = 0; i < count; i++)
    {
        output[i] = Marshal.PtrToStringAnsi(buffer[i]);
        Marshal.FreeHGlobal(buffer[i]);
    }
    

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