0

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 ?

1

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.