[Mono-list] Failing dlopen on Linux via DllImport with error message 'dlopen: invalid caller'

Jonathan Pryor jonpryor at vt.edu
Tue Nov 26 00:20:54 UTC 2013

On Nov 25, 2013, at 5:47 PM, Jean-Michel.Perraud at csiro.au wrote:
>      [DllImport("libdl")]
>      [return: MarshalAs(UnmanagedType.LPStr)]
>      private static extern string dlerror();

You should (almost?) never use `string` (or any other reference type) as the return type in a P/Invoke method:

> The CLI assumes that all memory that is passed between the CLI/unmanaged code boundary is allocated via a common memory allocator. The developer does not get a choice in which memory allocator is used. For managed code, the Marshal.AllocCoTaskMem method can be used to allocate memory, Marshal.FreeCoTaskMem is used to free the memory allocated by Marshal.AllocCoTaskMem, andMarshal.ReAllocCoTaskMem is used to resize a memory region originally allocated by Marshal.AllocCoTaskMem.
> Since classes are passed by reference, a pointer is returned, and the runtime assumes that it must free this memory to avoid a memory leak.

You should instead use IntPtr as the return type, then use Marshal.PtrToStringAnsi() to convert the IntPtr into a string.

 - Jon

More information about the Mono-list mailing list