[Mono-dev] Marshalling C-strings that need to be g_free()d

Robert Jordan robertj at gmx.net
Tue Jul 7 14:17:16 EDT 2009


Jon Shemitz wrote:
> Sorry for the newbie question, but my Windows .NET experience doesn't
> help me here, nor does MonoDoc or Google. (I'm sure I just don't know
> how to ask the right questions, yet, as this must be a FAQ):
> 
> If I have a C function like
> 
> void caller_owns_string(char** out_string);
> 
> How do I tell PInvoke that I 'own' the returned UTF8 string, and that
> the marshaller needs to g_free() *out_string after converting it to
> System.String?

Untested:

[DllImport ...]
static extern void caller_owns_string (ref IntPtr ptr)

public static string caller_owns_string ()
{
	IntPtr ptr = IntPtr.Zero;
	caller_owns_string (ref ptr);
	if (ptr != IntPtr.Zero) {
		try {
			return Marshal.PtrToStringAuto (ptr);
		} finally {
			Marshal.FreeHGlobal (ptr);
		}
	}
	return null;
}

Note that this code is only working because Mono is
using GLib as well. This might change in the future.

It would be safer if you'd pinvoke g_free () as well and use it in
place of Marshal.FreeHGlobal.

Robert



More information about the Mono-devel-list mailing list