简体   繁体   中英

Using external C++ library with C#

I'm trying to include an external C++ library in my c# project. This is the prototype of the function that I want to use:

 unsigned char* heatmap_render_default_to(const heatmap_t* h, unsigned char* colorbuf)

This function is allocating memory for colorbuf :

colorbuf = (unsigned char*)malloc(h->w*h->h * 4);

Pinvoke:

[DllImport(DLL, EntryPoint = "heatmap_render_default_to", CallingConvention = CallingConvention.Cdecl)]
public static extern byte[] Render_default_to(IntPtr h, byte[] colorbuf);

I tried to use this function in a main method to test the library:

           var colourbuf = new byte[w * h * 4];
        fixed (byte* colourbufPtr = colourbuf)
            HeatMapWrapper.NativeMethods.Render_default_to(hmPtr, colourbuf);

When I try this I'm getting a Segmentation fault exception. Could someone help me with this ?

You are going to need to marshal the return value manually. Declare it as IntPtr :

[DllImport(DLL, EntryPoint = "heatmap_render_default_to", 
    CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr Render_default_to(IntPtr h, byte[] colorbuf);

You can copy the buffer using Marshal.Copy :

IntPtr buffPtr = Render_default_to(...);
var buff = new byte[w * h * 4];
Marshal.Copy(buffPtr, buff, 0, buff.Length);

You'll also need to arrange for the external code to export a deallocator for the unmanaged memory that is being returned. Otherwise you'll end up leaking this memory.

I'm assuming that you are managing to pass a heatmap_t* correctly in the first argument of Render_default_to . We cannot see any of your code to do that and it's perfectly plausible that you are getting that wrong also. Which could lead to a similar runtime error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM