在 C# 中使用外部 C++ 库

Using external C++ library with C#

我正在尝试在我的 C# 项目中包含一个外部 C++ 库。 这是我要使用的函数的原型:

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

此函数正在为 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);

我尝试在一个主要方法中使用这个函数来测试库:

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

当我尝试此操作时,出现了分段错误异常。 有人可以帮我解决这个问题吗?

您将需要手动编组 return 值。声明为 IntPtr:

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

您可以使用 Marshal.Copy 复制缓冲区:

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

您还需要安排外部代码为正在 returned 的非托管内存导出释放器。否则你最终会泄漏这段内存。

我假设您设法在 Render_default_to 的第一个参数中正确传递 heatmap_t*。我们看不到您执行此操作的任何代码,而且您也完全有可能弄错了。这可能会导致类似的运行时错误。