如何将wchar_t*从c++到c#作为输出参数或返回值?

时间:2022-09-01 16:40:45

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#级别。

1 个解决方案

#1


6  

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 the LPWSTR type defined in windows.h.

这并不像你想象的那么难……wchar_t *是什么?这种类型通常代表什么值?一个字符串。它等价于windows中定义的LPWSTR类型。

So, you marshal it as a string type. 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类,而不是字符串类型。

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. It's the only one with access to the unmanaged memory area where the string was allocated.

请记住,非托管c++代码必须释放字符串,以防止内存泄漏。它是唯一一个能够访问该字符串被分配的非托管内存区域的。

#1


6  

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 the LPWSTR type defined in windows.h.

这并不像你想象的那么难……wchar_t *是什么?这种类型通常代表什么值?一个字符串。它等价于windows中定义的LPWSTR类型。

So, you marshal it as a string type. 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类,而不是字符串类型。

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. It's the only one with access to the unmanaged memory area where the string was allocated.

请记住,非托管c++代码必须释放字符串,以防止内存泄漏。它是唯一一个能够访问该字符串被分配的非托管内存区域的。