[Mono-list] Embedded Mono using DllImport(__Internal) and returning string

Jonathan Pryor jonpryor at vt.edu
Mon Mar 12 20:39:51 UTC 2012

On Mar 12, 2012, at 3:51 PM, efontana wrote:
> I'm using Embedded Mono and P/Invoke DllImport.   If I have a method which returns a string
> The corresponding "C" method should strdup the string right?

Probably not. During string marshaling, the pointer returned from CSharp_Test_ReturnString() will be freed "as if" through System.Runtime.InteropServices.Marshal.FreeCoTaskMem(), which is platform-specific. On Windows, this is CoTaskMemFree(). On non-Windows, this is g_free().

Either way, unless g_free() is aliased as free(3), strdup() will not allocate memory from the appropriate heap.

Consequently, you should explicitly allocate your memory with the correct memory allocator and strcpy() the value.

 - Jon

More information about the Mono-list mailing list