Try does not catch exception in DllImport function

泄露秘密 提交于 2019-12-04 19:25:39


I call C++ function from C# project:

public static extern int FillSlist(out string slist);

and then

  FillSlist(out slist);

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?


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


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