2013-04-11 47 views
0

我有一個用C編寫的DLL文件。我嘗試在我的C#代碼中使用C DLL(ImportDLL)。我的方法返回參數。 C法是正確調用,但過程中墜毀,並給出錯誤**"System.AccessViolationException: Attempted to read or write protected memory.AccessViolationExceptiond:試圖讀/寫保護的內存

這通常是指示其他內存已損壞「**過程完成之後。

我的C聲明

int preProcessAndBestImagesC(
     char* ..., 
     size_t* ..., 
     char** ..., 
     size_t* ..., 
     (struct)* ..., 
     size_t* ..., 
     int** ..., 
     (struct)** ..., 
     int ..., 
     int printStatus 
    ); 

我C#聲明

[DllImport(@"abc.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true, BestFitMapping = true, EntryPoint = "xxx")] 
    [return: MarshalAs(UnmanagedType.I4)] 
    unsafe private static extern int xxx(
     String p_ ...,            
     [MarshalAs(UnmanagedType.I2)] out UInt16 p_numImageFilesOrDirs, 

     String[] p_vecImageFilesOrDirs,    

     [MarshalAs(UnmanagedType.I2)] out UInt16 ..., 
     [MarshalAs(UnmanagedType.LPArray)] out (struct)[] ..., 
     [MarshalAs(UnmanagedType.I2)] out UInt16 ..., 
     out Int16[] ..., 
     [MarshalAs(UnmanagedType.LPArray)] out (struct)[] ..., 
     [MarshalAs(UnmanagedType.I2)] Int16 ..., 
     [MarshalAs(UnmanagedType.I2)] Int16 ... 
    ); 

有誰知道問題是什麼?

+0

您是否嘗試過Google?我很確定你已經找到了一些有用的答案,即使在這裏在stackoverflow。 – 2013-04-11 08:23:34

回答

0

沒有代碼是很難回答你的問題,但你可以使用下面的步驟,通過MSDN

轉到建議

工具 - >選項

Debugging->常規

不選擇選項「抑制模塊負載的JIT優化「

+0

我嘗試這個解決方案,但它不適合我。 – mmpatel009 2013-04-12 11:37:26

0

該聲明,例如編組參數cdecl/stdcall可能是錯誤的。

它也可能是數據執行保護(DEP)問題。在這種情況下,請在postbuild事件中使用

editbin.exe /NXCOMPAT:NO "$(TargetPath)" 

+0

請提供更多詳細信息,提前致謝。 – mmpatel009 2013-04-11 13:23:35

+0

看看你在這裏發佈的其他問題(http://stackoverflow.com/questions/15925884/an-unhandled-exception-of-type-system-executionengineexception-occurred-in-xxx),它可能是一個編組問題。 編輯您的問題,並向我們展示C中函數的原始簽名以及C#中的DllImport語句。 – 2013-04-12 08:27:17

+0

請在c#中看到我的c聲明和c#DLLImport語句,並告訴我在我的c#代碼中需要哪些更改。 – mmpatel009 2013-04-12 10:39:46

0

我建議如下:

考慮到DLL返回一個指針到內存中,請確保您的編組數據/參數。您可以使用INTPTR指向由DLL分配的內存。

此外,請確保DLL不會隱式刪除分配的內存。如果是這樣,請考慮重新編寫DLL代碼(如果可能)

希望這有助於。

相關問題