Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Marshalling unmanaged unicode string to .net. High chars replaced with question marks

Tags:

c++

c#

swig

This may or may not be a SWIG question.

I am trying to return a std::wstring by value from a C++ function to C#. The returned string has a mixture of plain old English chars and Hebrew chars. The English chars come through fine, but the Hebrew chars are being converted to the question mark symbol at some point.

I am using SWIG to generate the marshalling code. Stepping through it all with a debugger, it gets to the following SWIG code...

static string CreateWString([MarshalAs(UnmanagedType.LPWStr)]IntPtr cString) {
    string str = System.Runtime.InteropServices.Marshal.PtrToStringUni(cString);
    return str;
}

At this point str looks perfect.

Next this is returned to the SWIG-generated C++ code which returns the str as a void*.

Then the void* becomes a .net string again in the calling code. In the calling code, all the hebrew chars are ? marks.

Any ideas what's causing this?

Edit:

Further information

As soon as CreateWString returns to the C++ caller you can see the pointer in the debugger looks to be an ANSI string with ? marks in it. So it seems that .net is performing some sort of conversion on the string before it returns to the caller. Does that sound right? How can I control that?

Edit 2: It seems I need to do MarshallAs on the return type CreateWString to stop .net from converting to a TCHAR type (?)

like image 653
bluedog Avatar asked Oct 14 '11 01:10

bluedog


1 Answers

Modify the CreateWString definition to:

[return: MarshalAs(UnmanagedType.LPWStr)]
static string CreateWString([MarshalAs(UnmanagedType.LPWStr)]IntPtr cString)

See the examples in the MarshalAsAttribute documentation.

like image 199
Jim Mischel Avatar answered Oct 01 '22 11:10

Jim Mischel