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

I tried to do this in many ways, but no one works. Does anyone have the right example? I just want to move the wchar_t* value from the function to the C # level.

+6
source share
1 answer

It is not as difficult as you think it is ... What is wchar_t* ? What value does this type typically represent? Line. This is equivalent to the LPWSTR type defined in windows.h .

So you marshal it as a string type. However, since this is an out parameter (or return value), you need to use the StringBuilder class at the end of C #, not the type string .

The P / Invoke syntax would look something like this:

 [DllImport("MyLib.dll")] public static extern void MyFunction(StringBuilder str); 

And to use it, 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 unmanaged C ++ code must free the line to prevent memory leak. He is the only one who has access to the unmanaged memory area where the line was allocated.

+6
source

Source: https://habr.com/ru/post/888769/


All Articles