如何在C#中从指针读取字符串到缓冲区
如何从这个 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);
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果将数据类型从 byte* 更改为 IntPtr,这可能会起作用:
Marshal.PtrToStringAnsi
或
string
构造函数之一(其中之一还包含Encoding
参数):字符串构造函数
If you change the data type from byte* to IntPtr this might work:
Marshal.PtrToStringAnsi
Or one of the
string
constructors (one of them also includes anEncoding
parameter):String Constructors
Marshal.AllocHGlobal(int) 加上 Marshal.PtrToStringAuto(IntPtr, int) 也许?
一些代码上下文会很好,因为我假设您已经使用 p/invoke 或其他一些技巧将
byte*
强制转换为IntPtr
。基本上,调用您的函数来获取缓冲区大小,使用 AllocHGlobal() 分配缓冲区,再次调用它,读入字符串,然后释放缓冲区(使用 Marshall.FreeHGlobal(IntPtr) )。当然,这是假设您可以使用 Marshall 的分配器。
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 anIntPtr
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 (usingMarshall.FreeHGlobal(IntPtr)
). This is assuming you can use Marshall's allocator, of course.