[Mono-list] What is Correct way to marshal wchar_t ?
Dan.Maser at inin.com
Wed Jun 3 13:31:27 EDT 2009
I've found that you have two choices:
1. If you have source to the library you're interop'ing to, you can make the C interface take a "unsigned short*" instead of "wchar_t*" and it will work using the managed CharSet.Unicode for both systems. Of course your C code will have cast the paramter to a wchar_t* on windows but use a conversion function between UTF-16 and UCS-4 or UTF-8 on the non-windows library.
2. You can use C#'s custom marshal code to marshal as 2 bytes wide on windows and 4 bytes wide elsewhere and leave your C code using wchar_t everywhere. See the interfaces of System.Runtime.InteropServices.ICustomMarshaler and the attribute "[MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(YourClassDerivedFromICustomMarshaler))]". If you need an example of this let me know but the MSDN documentation using these classes should be enough for you to follow.
From: mono-list-bounces at lists.ximian.com [mailto:mono-list-bounces at lists.ximian.com] On Behalf Of ptr2009
Sent: Wednesday, June 03, 2009 11:54 AM
To: mono-list at lists.ximian.com
Subject: [Mono-list] What is Correct way to marshal wchar_t ?
I am trying to marshal strings from managed code to native code using
DllImport. Marshalling both wchar_t* and char* works under mono on a windows
But on mac os x wchart_t marshalling does not seem to work. The wchar_t* is
all junk. I have tried to search this forum and people have talked about it
and it seems to have been fixed.
Am I missing something ? I have experimented with CharSet.Unicode on
DllImport and it still doesnt work ?
What is the recommended way ?
My cs files is something like this
[DllImport("Test.dll", EntryPoint = "Global_PrintStringW")]
public static extern void Global_PrintStringW(
[DllImport("Test.dll", EntryPoint = "Global_PrintStringA")]
public static extern void Global_PrintStringA(string arg1);
private static void StringMarshallingTest()
string newString = "This is a cool string";
Console.WriteLine("Global_PrintStringA Test ");
Console.WriteLine("Global_PrintStringW Test ");
My cpp file is something like this
EXPORT_API void Global_PrintStringW(const wchar_t * str)
std::wcout << "Global_PrintStringW called with " << str << std::endl;
EXPORT_API void Global_PrintStringA(const char* str)
std::wcout << "Global_PrintStringA called with " << str << std::endl;
View this message in context: http://www.nabble.com/What-is-Correct-way-to-marshal-wchar_t---tp23855173p23855173.html
Sent from the Mono - General mailing list archive at Nabble.com.
Mono-list maillist - Mono-list at lists.ximian.com
More information about the Mono-list