C#调用C++ dll中uchar*参数

时间:2025-03-15 07:44:13

我的方式是:
C++程序中的uchar*->C#程序中的IntPtr->byte[]

当然很多人都说直接:
C++程序中的uchar*->C#程序中byte[]

但是我的实践过程中,在实时性较高的程序中,第二种方式总是会让数据加载不完全,导致程序经常崩溃,具体原因不知。

另外需要注意的是,要及时释放IntPtr内存。

[DllImport("Yourc++File", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr YourCplusplusFunction();
int SIZE = xxx;
byte[] buffer = new byte[SIZE];
...
IntPtr ptr = Marshal.AllocHGlobal(SIZE);
ptr = YourCplusplusFunction();
Marshal.Copy(ptr, buffer, 0, SIZE);
Marshal.FreeHGlobal(ptr);

相关文章