Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try does not catch exception in DllImport function

Tags:

c++

c#

I call C++ function from C# project:

[System.Runtime.InteropServices.DllImport("C.dll")]
public static extern int FillSlist(out string slist);

and then

try
{
  FillSlist(out slist);
}
catch
{
}

C++ dll is protected by third-party tool, so some code is being performed before FillSlist is really executed. Something really bad happens while this third-party code is executed and the program stops working at all. Neither "try" isolates the problem nor "AppDomain.CurrentDomain.UnhandledException" is executed.

Is there anything that can help to isolate crash of C++ function from C# calling code?

like image 963
Alex Avatar asked Feb 26 '10 18:02

Alex


1 Answers

Is this running on CLR 4.0? If so ...

If an exception does not get caught in an open catch block as demonstrated in your code it's because the CLR considers it a corrupted state exception and is by default not handled by user code. Instead it propagates up and causes the process to terminate.

It does this for a reason for these types of exceptions there is no action managed code can take to correct the problem. The only possible solution is to terminate the process.

You can override this behavior by adding an HandledCorruptedStateException attribute to the method. But generally speaking this is a bad idea.

More details

  • http://msdn.microsoft.com/en-us/magazine/dd419661.aspx

If not then it's possible the program is simply crashing out in native code and execution never properly returns to managed code.

like image 169
JaredPar Avatar answered Oct 20 '22 00:10

JaredPar