如何读取从C#中的指针到缓冲区的字符串
-
21-09-2019 - |
题
如何从此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 );
其他提示
元帅。Allochglobal(INT) 加 元帅。 也许?
某些代码上下文会很好,因为我假设您已经在强迫 byte*
进入 IntPtr
使用P/Invoke或其他一些技巧。
基本上,调用您的功能以获取缓冲区大小,使用缓冲区使用 AllocHGlobal()
, ,再次调用它,读取字符串,然后释放缓冲区(使用 Marshall.FreeHGlobal(IntPtr)
)。当然,这是假设您可以使用Marshall的分配器。
不隶属于 StackOverflow