【问题标题】:Catching native code exceptions in .NET在 .NET 中捕获本机代码异常
【发布时间】:2014-02-20 23:16:26
【问题描述】:

我目前正在使用带有专有包装器的 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)抛出。这在某种程度上是一个真正的问题,因为异常会破坏我的整个应用程序!

非常感谢任何帮助。

【问题讨论】:

  • 这不能直接完成。处理本机代码中的异常,并在发生异常时从本机代码返回properdata。在托管代码中,您可以通过检查返回的值/数据来了解是否发生任何异常。
  • @Narendra 异常可能发生在 DirectX 中,正如我在问题中提到的,它是一个专有组件。我无法改变它的任何方法来处理异常。

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


【解决方案1】:

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

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++) 代码中的所有内容(不确定你是否可以 PInvoke 它):

//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);

【讨论】:

    猜你喜欢
    • 2012-07-17
    • 1970-01-01
    • 2010-09-14
    • 1970-01-01
    • 2019-03-10
    • 1970-01-01
    • 2012-08-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多