我如何元帅为wchar_t *从C ++到C#作为out参数或返回值? [英] How do I marshal wchar_t* from C++ to C# as an out parameter or return value?
问题描述
我试图做到这一点的方法很多,但没有一个是工作。有没有人有一个正确的榜样呢?我只是想从一个函数到C#的水平移动 wchar_t的*
值。
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的*
?什么样的价值确实该类型通常重新present?一个字符串。这是等同于 LPWSTR
在 WINDOWS.H
类型来定义。
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
.
所以,你封送它作为一个字符串
键入。然而,因为它是一个退出
参数(或返回值),你需要使用<一个href="http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx"><$c$c>StringBuilder$c$c>类 C#的结束,而不是字符串
键入
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.
在P / Invoke的语法将是这个样子:
The P/Invoke syntax would look something like this:
[DllImport("MyLib.dll")]
public static extern void MyFunction(StringBuilder str);
和使用它,你首先声明 StringBuiler
类具有适当能力的一个实例,然后调用函数:
And to use it, you first declare an instance of the StringBuiler
class with the appropriate capacity, and then call the function:
StringBuilder myString = new StringBuilder(255);
MyFunction(myString);
记住,非托管C ++ code必须释放在字符串中以prevent内存泄漏。它是唯一一个能够访问字符串在何处分配的非托管内存区域。
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.
这篇关于我如何元帅为wchar_t *从C ++到C#作为out参数或返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!