简体   繁体   中英

Marshaling unmanaged char** to managed string[]

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,int MaxLength)
{
    for(int i=0;i<Count;i++)
    {
        char buff[25];
        _itoa(i,buff,10);

        strncpy(OutBuff[i],buff,MaxLength);
    }
}

I suppose that the C# prototype must be next:

    [DllImport("StringsScetch.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
    private static extern void TestArray([MarshalAs(UnmanagedType.LPArray)] IntPtr[] OutBuff, int Count, int MaxLength);

But should I prepare IntPtr objects to receive strings from unmanaged code?

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]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM