我在 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 对象来接收来自非托管代码的字符串吗?
因此 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]);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)