2010-08-06 62 views
6

我試圖調用,將其包裝成一個DLL下面的C++函數:如何在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文件中......任何人有任何想法?

+0

你可能想看看這個問題:http://stackoverflow.com/questions/289076/how-can-i-pass-a-pointer-to-an-array-using- p-invoke-in-c – Bobby 2010-08-06 18:11:39

+1

來自'rectifyImage'的返回值是否應該被釋放,如果是,怎麼辦? – 2010-08-06 18:25:57

+0

rectifyImage的返回值用於創建C#位圖對象,然後釋放它。我還沒有試圖弄清楚如何實際上釋放它。 – Tim 2010-08-06 18:29:06

回答

2

這很可能是因爲該方法的調用約定並不像編組人員猜測的那樣。您可以在DllImport屬性中指定約定。

因爲這不是'不安全'的代碼,所以你不需要'C'聲明中的'unsafe'關鍵字。也許你正在用一個「固定」指針試着它,忘了在發佈之前刪除不安全的關鍵字?

1

不知道這是否是您的問題,但通常C++指針映射到IntPtr。所以嘗試修改您的import語句是:

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

不知道爲什麼我被拒絕了,但我花時間回答了這個問題,所以我至少期待一個評論,爲什麼我的回答不符合你的喜好!你真的嘗試過我的建議,它沒有工作? – 2013-04-19 20:13:29

0

rectifyImage是數據塊要發送的塊找ponter到的第一個字節。嘗試imageData [0]

+0

這不會起作用,因爲編組會傳遞第一個字節的副本,而不是其參考。所以你必須使用不安全的代碼來做到這一點,並且傳遞'&imageData [0]'而不是'imageData [0]'。 – Luaan 2014-05-07 07:35:05

相關問題