如何从 C++ 封送 wchar_t*到 C# 作为输出参数或返回值?
我尝试过很多方法来做到这一点,但没有一个有效。有人有正确的例子吗?我只想将 wchar_t*
值从函数移至 C# 级别。
I have tried to do this in many ways, but none is working. Does anyone have a correct example for this? I just want to move the wchar_t*
value from a function to the C# level.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这并不像您想象的那么困难...
wchar_t*
是什么?该类型通常代表什么值?一根绳子。它相当于windows.h
中定义的LPWSTR
类型。因此,您将其编组为
string
类型。但是,由于它是一个out
参数(或返回值),因此您需要使用 C# 端的StringBuilder
类,而不是string
类型。P/Invoke 语法如下所示:
要使用它,首先声明具有适当容量的 StringBuiler 类的实例,然后调用该函数:
请记住,非托管 C++ 代码必须释放字符串以防止内存泄漏。它是唯一可以访问分配字符串的非托管内存区域的内存区域。
This isn't as difficult as you think it is... What is
wchar_t*
? What value does that type typically represent? A string. It's the equivalent to theLPWSTR
type defined inwindows.h
.So, you marshal it as a
string
type. However, since it's anout
parameter (or a return value), you'll need to use theStringBuilder
class on the C# end, rather than thestring
type.The P/Invoke syntax would look something like this:
And to use it, you first declare an instance of the
StringBuiler
class with the appropriate capacity, and then call the function:Remember that the unmanaged C++ code must free the string in order to prevent a memory leak. It's the only one with access to the unmanaged memory area where the string was allocated.