[Mono-list] String Marshalling for P/Invoke

Marcus mathpup@mylinuxisp.com
Wed, 8 Jan 2003 21:42:50 -0600


Jaroslaw Kowalski recently brought up the point that

"When you write 'static string function(parameters)' the function is expected
to ALLOCATE the returned string on task heap (using CoTaskMemAlloc() under
Windows), so CLR will happily free the string when it's no longer used, but
unfortunately when you return the static pointer to the CLR, it will attempt
to free an unallocated memory block, which is a big BOOM."

I'm confused about how this works under Mono under Linux (and other POSIX-like 
systems) because most libraries allocate heap storage using glibc's malloc(), 
whereas Mono uses glib's -- not glibc's -- g_free() function to return freed 
memory to the pool. I've gotten conflicting answers over whether returning 
malloc()'ed memory with g_free() is legal or not. So far, I haven't observed 
any specific problems, but as someone working on Qt#, which passes strings 
back and forth a great deal, I'm concerned about the proper behavior.

Let me be more specific: Suppose under Mono for Linux that I have

[DllImport("libpeace", CharSet=CharSet.Ansi)]
static string stringFunction();

where stringFunction returns a pointer to a string whose storage was obtained 
using malloc(). Will Mono's runtime properly dispose of the string's storage? 
If so, how? Will mono call g_free() (is that okay, since the storage was 
obtained with malloc)?