在.NET中捕获本机代码异常

时间:2014-01-29 08:54:13

标签: c# c++ exception ffmpeg native-code

我目前正在使用ffmpeg使用专有包装器,我需要捕获有时在转码过程中发生的本机代码异常等。

我已经阅读了这些问题/答案:

https://stackoverflow.com/questions/10517199/cant-catch-native-exception-in-managed-code https://stackoverflow.com/questions/150544/can-you-catch-a-native-exception-in-c-sharp-code

然而,它们并没有真正有用,因为异常不会在我调用的函数期间发生,而是在ffmpeg库中并行运行并且被其他组件(如DirectX)抛出的完全不同的线程中。这是一个真正的问题,因为异常会拆除我的整个申请!

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

您可以使用这两个事件捕获从其他线程抛出的异常:

System.Windows.Forms.Application.ThreadException += Application_ThreadException;
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
// Set the unhandled exception mode to force all Windows Forms errors to go through our handler.
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

您可能还需要在App.config文件中设置以下内容:

<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
  <runtime>
    <legacyUnhandledExceptionPolicy enabled="1" />
  </runtime>
...

如果您无法使用托管代码,下面的代码将捕获本机(c ++)代码中的所有内容(不确定是否可以将其隐藏):

//Sets the handler for a pure virtual function call. 
_set_purecall_handler( &MyPureVirtualCallHandler );

// Sets the handler function to be called when invalid parameters are passed to C runtime functions
_set_invalid_parameter_handler( &MyInvalidParameterHandler );

//Register an unhandled exception filter
SetUnhandledExceptionFilter(&UnhandExceptionFilter);
相关问题