質問
pinvoke コードを使用して C 関数を呼び出そうとしています。この関数はバッファにデータを書き込みます。
この構造は、長さの DWORD として設定され、その後に文字列が続きます。IntPtr から文字列を抽出するにはどうすればよいですか?
IntPtr buffer = Marshal.AllocHGlobal(nRequiredSize);
PInvokedFunction(buffer, nRequiredSize);
string s = Marshal.PtrToStringAuto(buffer + 4); //this is an error.
Marshal.FreeHGlobal(buffer);
解決
これを行う必要があります:
IntPtr sBuffer = new IntPtr( buffer.ToInt64() + 4 );
string s = Marshal.PtrToStringAuto( sBuffer );
コードは64ビットで安全です。
他のヒント
UnmanagedMemoryStreamの使用はちょっとしたハックのように思えますが、私が思いついたのは次のものでした。
IntPtr buffer = Marshal.AllocHGlobal((int)nRequiredSize);
PInvokedFunction(buffer, nRequiredSize);
UnmanagedMemoryStream memStream = new UnmanagedMemoryStream(buffer.ToPointer(), nRequiredSize);
memStream.Seek(4, SeekOrigin.Begin);
IntPtr ptr = new IntPtr(memStream.PositionPointer);
string s = Marshal.PtrToStringAuto(ptr);
Marshal.FreeHGlobal(buffer);
これはうまくいくようですが、気に入っているように思います マット・エリスの答え より良い。
[DllImport] の IntPtr を byte[] に変更しました。
//allocate the buffer in .Net
byte[] buffer = new byte[nRequiredSize];
//call the WIN32 function, passing it the allocated buffer
PInvokedFunction(buffer);
//get the string from the 5th byte
string s = Marshal.PtrToStringAuto(Marshal.UnsafeAddrOfPinnedArrayElement(buffer, 4));
所属していません StackOverflow