如何在C#中封送字节数组? 我试图调用下面的C++函数,它被封装成一个DLL: unsigned char * rectifyImage(unsigned char *pimg, int rows, int cols)

如何在C#中封送字节数组? 我试图调用下面的C++函数,它被封装成一个DLL: unsigned char * rectifyImage(unsigned char *pimg, int rows, int cols),c#,marshalling,byte,C#,Marshalling,Byte,我的导入语句如下所示: [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 rectifiedIma

我的导入语句如下所示:

[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'关键字,因为它不是'unsafe'代码。也许你在一个点上用一个“固定”指针尝试它,忘记在发布之前删除不安全的关键字?< /p> < p>不确定这是你的问题,但是一般C++指针映射到IntPtr。因此,请尝试将您的导入语句修改为:

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

整流图像正在为块中发送的数据寻找块中第一个字节的端口。尝试imageData[0]

您可能想看看这个问题:是否应该释放
rectityImage
的返回值,如果是,如何释放?rectityImage的返回值用于创建一个C#Bitmap对象,然后释放。我还没来得及弄清楚如何真正释放它。我不知道为什么我会被否决,但我花了时间来回答这个问题,所以我至少希望得到一个评论,为什么我的答案不符合你的喜好!你真的试过我的建议了吗?它不起作用了,因为封送员会传递第一个字节的副本,而不是它的引用。因此,您必须使用不安全的代码来执行此操作,并传递
&imageData[0]
,而不仅仅是
imageData[0]