[Mono-dev] Marshalling wchar_t

Jonathan Pryor jonpryor at vt.edu
Thu Jan 18 06:38:40 EST 2007

On Thu, 2007-01-18 at 12:03 +1100, Rajesh Gupta wrote:
> ...I read that it was due to the number of bytes used by wchar_t in
> Windows and Linux. Mono seems to be marshalling it like windows
> wchar_t even on Linux and thus the junk characters. Is there a way I
> can get wchar_t to work through marshalling?

Yes, but you need to do things manually on Linux, as wchar_t on Linux is
UTF-32, while Mono's LPWStr is UTF-16.  You would need to change
authenticate() to:

	[DllImport ("AuthController")]
	private static uint authenticate (
		int hwnd,
		ref ModuleAndType[] modules,
		int size,
		IntPtr inToken,
		ref IntPtr outToken

Calling would become:

	IntPtr inToken = Mono.Unix.UnixMarshal.StringToHeap ("token",
	ref IntPtr _outToken = IntPtr.Zero;
	authenticate (hwnd, modules, size, inToken, ref _outToken);
	Mono.Unix.UnixMarshal.FreeHeap (inToken);
	string outToken = Mono.Unix.UnixMarshal.PtrToString (_outToken,
	// how was _outToken allocated?  You might need:
	// Mono.Unix.UnixMarshal.FreeHeap (_outToken)

i.e. you'd manually convert the wchar_t parameters on Linux.

Notes: System.Text.Encoding.UTF32 is a .NET 2.0 member,
Mono.Unix.UnixMarshal is in Mono.Posix.dll, and Mono.Unix.UnixMarshal
_should_ be portable to Win32 if necessary.  (Worst case you can always
copy the code into your own project, as Mono.Posix.dll is MIT/X11 code.)

 - Jon

More information about the Mono-devel-list mailing list