c# - 有没有办法预测 `Marshal.GetExceptionForHR(code, pointers)` 会抛出 `AccessViolationException`

标签 c# exception marshalling access-violation

我有一整套相互关联的问题。我想独立地知道所有这些问题的答案,所以*是的*,其中一些似乎是 X-Y 问题;但我确实想知道他们的解决方案!请参阅问题末尾以获取本集中其他问题的列表。

我有一种情况,调用Marshal.GetExceptionForHR(code, pointers)抛出 AccessViolationException .

显然这是一个非常糟糕的事情。太糟糕了try...catch只是对我耸耸肩,然后四处走动……我不知道这是一件事:(

假设“调用 .GetExceptionForHR() 是我想要做的事情”的前提(有关这是否是一个好主意的讨论,请参阅其他问题!)。

进一步假设任何导致 AccessViolation在某些情况下是不可避免的。

鉴于这些前提,有没有办法提前预测调用它们的方法会爆炸?
相当于 TryGetExceptionForHR()这将返回 false而不是炸毁我的整个程序。

此问题集中的其他问题。

  • C#: How do I prevent a pipe reading error, when closing the exe on one end of a DuplexChannel connected by Named Pipes?
  • Ascertain reason for Channel Fault in WCF+NamedPipes
  • Is using the `Marshal` static class in otherwise normal C# code unwise?
  • Is there a way to predict that `Marshal.GetExceptionForHR(code, pointers)` would throw an `AccessViolationException`
  • Is this a suitable use of `HandleProcessCorruptedStateExceptions`
  • 最佳答案

    只需查看 Microsoft 文档,Marshall.GetExceptionForHR不会抛出可以被捕获的异常。

    相反,他们建议使用 Marshall.ThrowExceptionForHR得到一个抛出的异常,然后你可以处理。使用 时不会抛出异常成功结果。

    如果你想使用 Marshall.GetExceptionForHR然后仔细检查是否使用了正确的指针。 IntPtr(0) IntPtr(-1) 时将使用当前的 IErrorInfo 接口(interface)将尝试仅从代码重构异常。
    GetExceptionForHR 也可能不是抛出意外的异常,而是仅从 catch block 返回意外异常,例如:

    catch(Exception ex)
    {
       return ex;
    };
    

    不幸的是,此时我不能 100% 确定,我正在尝试在 Microsoft 的 Github 上追踪 Marshall 类(class),并且我将自己尝试一些尝试,看看我是否能获得与您相同的效果。

    相关链接:
  • ThrowExceptionForHR
  • GetExceptionForHR
  • 关于c# - 有没有办法预测 `Marshal.GetExceptionForHR(code, pointers)` 会抛出 `AccessViolationException`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60424851/

    相关文章:

    C# 编码(marshal) uint*& 参数

    c# - 如何将 Action<string> 添加到界面?

    c# - SQL命令字符串中@whatever的存在给我一个 fatal error

    c# - WPF 将第三方 ResourceDictionary 添加到 App.xaml?

    c# - 如何在 IIS 中授予对 Web API 应用程序的写入权限?

    java - 我可以简化这三个 catch block 吗?

    asp.net - 在ASP.NET中如何识别/处理404异常?

    java - 当我向 URL 发布 https 请求时出现 "unable to find valid certification path to requested target"

    c# - 如何将结构数组从 C++ dll 返回到 C#

    c# - 如何调用 C# 委托(delegate)以从 native C 最简单的方式传递字符串数组?