私はスタックオーバーフローの質問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