繁体   English   中英

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

[英]How can you Marshal a byte array in C#?

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

unsigned char * rectifyImage(unsigned char *pimg, int rows, int cols)

我的import语句如下所示:

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

我的调用例程如下所示:

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);

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

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

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

这很可能发生,因为该方法的调用约定并不像编组人员猜测的那样。 您可以在DllImport属性中指定约定。

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

不确定这是否是你的问题,但一般来说C ++指针映射到IntPtr。 所以尝试将import语句修改为:

[DllImport("mex_rectify_image.dll")]
unsafe public static extern IntPtr rectifyImage(
IntPtr pData, int rows, int columns);

rectifyImage正在查找块中第1个字节的ponter,用于在块中发送的数据。 试试imageData [0]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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