Try does not catch exception in DllImport function

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

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/2344087/try-does-not-catch-exception-in-dllimport-function

标签

工具导航Map