How do I marshal wchar_t* from C++ to C# as an out parameter or return value?

耗尽温柔 提交于 2019-12-17 19:29:07

问题


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.


回答1:


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.

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.

The P/Invoke syntax would look something like this:

[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:

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.



来源:https://stackoverflow.com/questions/6089214/how-do-i-marshal-wchar-t-from-c-to-c-sharp-as-an-out-parameter-or-return-valu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!