質問

このC ++ DLL呼び出しからC#のエラー文字列を読み取るにはどうすればよいですか?

//
//  PARAMETERS:
//      objptr
//          Pointer to class instance.
//
//      pBuffer
//          Pointer to buffer receiving NULL terminated error message string.   
//          If this value is zero, the function returns the required buffer size, in bytes,
//          and makes no use of the pBuffer. 
//
//      nSize
//          Size of receiving buffer.
//          If this value is zero, the function returns the required buffer size, in bytes,
//          and makes no use of the pBuffer. 
//
//  RETURN VALUES:
//      If pBuffer or nSize is zero, the function returns the required buffer size, in bytes.
//      If the function succeeds, the return value is number of bytes copied into pBuffer.
//      If function fails return value is 0.
//
extern unsafe int GetError(uint objptr, byte* pBuffer, int nSize);

ありがとう!

役に立ちましたか?

解決

byte[] buffer = new byte[1000];
int size;
unsafe
{
  fixed ( byte* p = buffer )
  {
    size = GetError( ???, p, buffer.Length ); 
  }
}
string result = System.Text.Encoding.Default.GetString( buffer, 0, size );

他のヒント

データ型をBYTE*からINTPTRに変更すると、これが機能する可能性があります。

Marshal.ptrtostringansi

またはの1つ string コンストラクター(そのうちの1つには、 Encoding パラメーター):

文字列コンストラクター

Marshal.Allochglobal(int) プラス Marshal.ptrtostringauto(intptr、int) 多分?

私はあなたがすでに強制していると仮定しているので、いくつかのコードのコンテキストがいいでしょう byte*IntPtr P/Invokeまたはその他のトリックを使用します。

基本的に、バッファサイズを取得するために機能を呼び出し、使用してバッファーを割り当てます AllocHGlobal(), 、もう一度呼び出して、文字列を読んでからバッファを解放します(使用して Marshall.FreeHGlobal(IntPtr))。もちろん、これはマーシャルのアロケーターを使用できると仮定しています。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top