簡體   English   中英

在C#中處理來自非托管dll的異常

[英]Handling exception from unmanaged dll in C#

我有用C#編寫的以下函數

public static string GetNominativeDeclension(string surnameNamePatronimic)
{
    if(surnameNamePatronimic == null) 
       throw new ArgumentNullException("surnameNamePatronimic");

IntPtr[] ptrs = null;
try
{
    ptrs = StringsToIntPtrArray(surnameNamePatronimic);

    int resultLen = MaxResultBufSize;
    int err = decGetNominativePadeg(ptrs[0], ptrs[1], ref resultLen);
    ThrowException(err);
    return IntPtrToString(ptrs, resultLen);
}
catch
{
    return surnameNamePatronimic;
}
finally
{
    FreeIntPtr(ptrs);
}

}

函數decGetNominativePadeg在非托管dll中


[DllImport("Padeg.dll", EntryPoint = "GetNominativePadeg")]
private static extern Int32 decGetNominativePadeg(IntPtr surnameNamePatronimic,
    IntPtr result, ref Int32 resultLength);

並拋出異常: Attempted to read or write protected memory. This is often an indication that other memory is corrupt Attempted to read or write protected memory. This is often an indication that other memory is corrupt
C#代碼中的catch實際上並沒有捕獲它。 為什么? 如何處理這個異常?
謝謝您的幫助!

“CLR不再為托管代碼中的異常處理程序提供損壞的進程狀態的異常。”

.NET Framework 4遷移問題

只需將其添加到配置文件: http//msdn.microsoft.com/en-us/library/dd638517.aspx

如果IntPtr result參數是從函數中接收值,則必須將其標記為ref。

我沒有看到ptrs[1]在傳遞之前被賦予任何值。

嘗試將定義更改為:

[DllImport("Padeg.dll", EntryPoint = "GetNominativePadeg")]
private static extern Int32 decGetNominativePadeg(IntPtr surnameNamePatronimic,
    **ref** IntPtr result, ref Int32 resultLength);

原因可能是它試圖寫入“結果”,標記為僅輸入。

你可能已經關閉了非托管代碼的調試。

“啟用非托管代碼調試選項”必須在“調試”部分下檢查項目屬性。 在此之后,調試過程中會顯示異常。

問題解決了。 我發現當使用第4個框架時我有這個問題,當使用3.5時 - 我沒有。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM