如何在C#中编写一个字节数组?

Tim*_*Tim 7 c# byte marshalling

我正在尝试调用以下包含在DLL中的C++函数:

unsigned char * rectifyImage(unsigned char *pimg, int rows, int cols)
Run Code Online (Sandbox Code Playgroud)

我的import语句如下所示:

[DllImport("mex_rectify_image.dll")]
unsafe public static extern IntPtr rectifyImage(
byte[] data, int rows, int columns);
Run Code Online (Sandbox Code Playgroud)

我的调用例程如下所示:

byte[] imageData = new byte[img.Height * img.Width * 3];
// ... populate imageData
IntPtr rectifiedImagePtr = rectifyImage(imageData, img.Height, img.Width);
Byte[] rectifiedImage = new Byte[img.Width * img.Height * 3];
Marshal.Copy(rectifiedImagePtr, rectifiedImage, 0, 3 * img.Width * img.Height);
Run Code Online (Sandbox Code Playgroud)

但是,我不断收到运行时错误:

System.AccessViolationExceptionxxx.dll中出现类型的第一次机会异常尝试读取或写入受保护的内存.这通常表明其他内存已损坏.

我只是想知道问题是否在于我正在整理我的数据或导入的DLL文件......任何人都有任何想法?

Ter*_*ver 2

发生这种情况的原因可能是该方法的调用约定与编组器猜测的不同。您可以在 DllImport 属性中指定约定。

您不需要在此处的 C# 声明中使用“不安全”关键字,因为它不是“不安全”代码。也许您曾在某一时刻尝试使用“固定”指针,但忘记在发布之前删除不安全的关键字?