[Mono-bugs] [Bug 375222] DllImported function with string return crashes Mono

bugzilla_noreply at novell.com bugzilla_noreply at novell.com
Sun Mar 30 13:49:34 EDT 2008


https://bugzilla.novell.com/show_bug.cgi?id=375222

User jpryor at novell.com added comment
https://bugzilla.novell.com/show_bug.cgi?id=375222#c8


Jonathan Pryor <jpryor at novell.com> changed:

           What    |Removed                                         |Added
----------------------------------------------------------------------------
                 CC|                                                |jpryor at novell.com




--- Comment #8 from Jonathan Pryor <jpryor at novell.com>  2008-03-30 11:49:34 MST ---
I suspect that this will cause a memory leak on Windows, as .NET documents that
it will use CoTaskMemFree() to free the memory of the return value of functions
returning reference types.

Since ole32.dll!CoTaskMemFree() != msvcrt.dll!free(), I imagine that this would
leak the memory instead of freeing it (and that's assuming you use msvcrt.dll,
as there are many different C runtime libraries on Windows...).

If you need to return a string constant or return a pointer to dynamically
allocated memory not allocated with CoTaskMemAlloc (.NET) or g_malloc (Mono),
you should instead use System.IntPtr as the P/Invoke return type and manually
marshal and free the returned pointer:

  [DllImport (...)]
  static extern IntPtr goo ();

  static void UseGoo ()
  {
    IntPtr p = goo ();
    string s = Marshal.PtrToStringAnsi (p);
    // Manually free `p' with the appropriate deallocation function if needed
  }


-- 
Configure bugmail: https://bugzilla.novell.com/userprefs.cgi?tab=email
------- You are receiving this mail because: -------
You are the QA contact for the bug.
You are the assignee for the bug.


More information about the mono-bugs mailing list