[英]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.