Handling exception from unmanaged dll in C#

我是研究僧i 提交于 2019-12-23 09:36:46

问题


I have the following function written in 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);
}

}

Function decGetNominativePadeg is in unmanaged dll


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

and throws an exception: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
The catch that is in C# code doesn't actually catch it. Why? How to handle this exception?
Thank you for your help!


回答1:


"The CLR no longer delivers exceptions for corrupted process state to exception handlers in managed code."

.NET Framework 4 Migration Issues.

Just add this to the config file: http://msdn.microsoft.com/en-us/library/dd638517.aspx




回答2:


If the IntPtr result parameter is to receive the value from within the function, it must be marked ref.

I don't see ptrs[1] being assigned any value before passing.

Try changing the definition to:

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

The reason probably is that it's trying to write to "result" which is marked as input-only.




回答3:


you have probably turned off debugging of unmanaged code.

"Enable unmanaged code debugging option" must be check in project properties under the Debug section. After this, the exception is shown in the debugging process.




回答4:


Problem solved. I found out that when using 4-th framework I have this problem, when using 3.5 - I don't.



来源:https://stackoverflow.com/questions/2854942/handling-exception-from-unmanaged-dll-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!