如何从此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 );

其他提示

如果将数据类型从字节*更改为intptr,则可能有效:

元帅

或其中之一 string 构造函数(其中之一还包括 Encoding 范围):

字符串构造函数

元帅。Allochglobal(INT)元帅。 也许?

某些代码上下文会很好,因为我假设您已经在强迫 byte* 进入 IntPtr 使用P/Invoke或其他一些技巧。

基本上,调用您的功能以获取缓冲区大小,使用缓冲区使用 AllocHGlobal(), ,再次调用它,读取字符串,然后释放缓冲区(使用 Marshall.FreeHGlobal(IntPtr))。当然,这是假设您可以使用Marshall的分配器。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top