我测试了堆栈溢出问题代码Marshaling unmanaged char** to managed string[],它运行良好。Unicode字符串和FreeHGlobal问题?
我试图将它转换为Unicode,然后我开始得到“句柄无效”。为什么?
我的修改后的代码:
_declspec(dllexport) void TestArray(wchar_t** OutBuff, int Count, int MaxLength)
{
for(int i=0; i<Count; i++)
{
wchar_t buff[25];
_itow(i, buff, 10);
wcsncpy(OutBuff[i], buff, MaxLength);
}
}
和C#的包装:
class Program
{
[DllImport("Native.dll", EntryPoint = "[email protected]@[email protected]", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void TestArray([MarshalAs(UnmanagedType.LPArray)]
IntPtr[] OutBuff, int Count, int MaxLength);
static void Main(string[] args)
{
int count = 10;
int maxLen = 50;
IntPtr[] buffer = new IntPtr[maxLen];
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.PtrToStringUni(buffer[i]);
Marshal.FreeHGlobal(buffer[i]); // Crash is here, when count is 1.
Console.WriteLine(output[i]);
}
Console.ReadKey();
}
}
那么,它适用于ANSI版本。如果直接修改会导致腐败,如何重写代码以传递字符串之间的动态数组? – Assaf