How to read string from pointer to buffer in C#
-
21-09-2019 - |
문제
How can I read the error string in C# from this C++ dll call?
//
// 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);
thanks!
해결책
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 );
다른 팁
If you change the data type from byte* to IntPtr this might work:
Or one of the string
constructors (one of them also includes an Encoding
parameter):
Marshal.AllocHGlobal(int) plus Marshal.PtrToStringAuto(IntPtr, int) perhaps?
Some code context would be nice, as I'm assuming that you're already coercing byte*
into an IntPtr
using p/invoke or some other trickery.
Basically, call your function to get the buffer size, allocate a buffer using AllocHGlobal()
, call it again, read the string in, then free the buffer (using Marshall.FreeHGlobal(IntPtr)
). This is assuming you can use Marshall's allocator, of course.
제휴하지 않습니다 StackOverflow