[Mono-dev] Specifying MarshallAs for [Out] StringBuilder

Jonathan Pryor jonpryor at vt.edu
Sun Mar 23 20:24:07 EDT 2008

On Sun, 2008-03-23 at 09:59 -0400, Debajyoti Bera wrote:
> 	But how I do manually unmarshall a StringBuilder ? I tried using Charset.Auto 
> and MarshalAs(LPTStr) - that did not help.

You don't -- StringBuilder is "special," and only supports the encodings
that DllImport supports.

Consequently, you need to do things manually; instead of this:

	[DllImport (...)]
	static extern void GetString (StringBuilder buf, int size);

you should do this:

	[DllImport (...)]
	static extern void GetString ([Out] byte[] buf, int size);

You can then use the normal encoding mechanism to convert the byte[] to
a string after the buffer is filled:

	byte[] buf = new byte[256];
	GetString (buf, buf.Length);
	string s = Encoding.GetEncoding (encodingName).GetString (buf);

 - Jon

More information about the Mono-devel-list mailing list