[英]How do I marshal wchar_t* from C++ to C# as an out parameter or return value?
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. 我只想将
wchar_t*
值从函数移动到C#级别。
This isn't as difficult as you think it is... What is wchar_t*
? 这并不像你想象的那么困难......什么是
wchar_t*
? What value does that type typically represent? 这种类型通常代表什么价值? A string.
一个字符串。 It's the equivalent to the
LPWSTR
type defined in windows.h
. 它等同于
windows.h
定义的LPWSTR
类型。
So, you marshal it as a string
type. 所以,你把它作为
string
类型编组。 However, since it's an out
parameter (or a return value), you'll need to use the StringBuilder
class on the C# end, rather than the string
type. 但是,由于它是
out
参数(或返回值),因此您需要在C#端使用StringBuilder
类 ,而不是string
类型。
The P/Invoke syntax would look something like this: P / Invoke语法看起来像这样:
[DllImport("MyLib.dll")]
public static extern void MyFunction(StringBuilder str);
And to use it, you first declare an instance of the StringBuiler
class with the appropriate capacity, and then call the function: 要使用它,首先要声明具有适当容量的
StringBuiler
类的实例,然后调用该函数:
StringBuilder myString = new StringBuilder(255);
MyFunction(myString);
Remember that the unmanaged C++ code must free the string in order to prevent a memory leak. 请记住,非托管C ++代码必须释放字符串以防止内存泄漏。 It's the only one with access to the unmanaged memory area where the string was allocated.
它是唯一可以访问分配字符串的非托管内存区域的人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.