Reputation: 6347
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?
Upvotes: 1
Views: 1864
Reputation: 31394
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]);
}
Upvotes: 4