我在DLL文件中有一个C ++函数(它使用多字节字符集选项编译):
_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);
}
}
我认为C#原型必须是下一个:
[DllImport("StringsScetch.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
private static extern void TestArray([MarshalAs(UnmanagedType.LPArray)] IntPtr[] OutBuff, int Count, int MaxLength);
但是我应该准备IntPtr对象来接收来自非托管代码的字符串吗?
答案 0 :(得分:4)
所以OutBuff基本上是一个指针数组 - 所以你需要创建一个IntPtr数组,其元素是有效的指针 - 即指向有效内存的IntPtr值。如下所示:
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]);
}