简体   繁体   English

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

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

I'm trying to call the following C++ function that's wrapped up into a DLL: 我正在尝试调用以下包含在DLL中的C ++函数:

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

My import statement looks like the following: 我的import语句如下所示:

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

And my call routine looks like the following: 我的调用例程如下所示:

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

However, I keep getting a runtime error: 但是,我不断收到运行时错误:

A first chance exception of type System.AccessViolationException occurred in xxx.dll Attempted to read or write protected memory. xxx.dll中发生System.AccessViolationException类型的第一次机会异常尝试读取或写入受保护的内存。 This is often an indication that other memory is corrupt. 这通常表明其他内存已损坏。

I'm just wondering if the fault lies in the way I'm marshaling my data or in my imported DLL file... anyone have any ideas? 我只是想知道问题是否在于我正在整理我的数据或导入的DLL文件......任何人都有任何想法?

This is likely occurring because the calling convention of the method is not as the marshaller is guessing it to be. 这很可能发生,因为该方法的调用约定并不像编组人员猜测的那样。 You can specify the convention in the DllImport attribute. 您可以在DllImport属性中指定约定。

You don't need the 'unsafe' keyword in the C# declaration here as it's not 'unsafe' code. 您不需要在C#声明中使用'unsafe'关键字,因为它不是'不安全'代码。 Perhaps you were trying it with a 'fixed' pointer at one point and forgot to remove the unsafe keyword before posting? 也许你在某一点尝试使用“固定”指针并忘记在发布之前删除不安全的关键字?

not sure if this is your problem, but in general C++ pointers map to IntPtr. 不确定这是否是你的问题,但一般来说C ++指针映射到IntPtr。 so try modifying your import statement to this: 所以尝试将import语句修改为:

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

rectifyImage Is looking for a ponter to a the 1st byte in a block for data you are sending in the block. rectifyImage正在查找块中第1个字节的ponter,用于在块中发送的数据。 Try imageData[0] 试试imageData [0]

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

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