Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling exception from unmanaged dll in C#

Tags:

c#

dll

unmanaged

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!

like image 917
StuffHappens Avatar asked May 18 '10 06:05

StuffHappens


1 Answers

"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

like image 199
David MC Coelho Avatar answered Oct 16 '22 02:10

David MC Coelho