AccessViolationException,尝试读取或写入受保护的内存

发布于 2024-08-27 13:58:06 字数 416 浏览 4 评论 0原文

我使用的 dll 包含用于与特定硬件交互的非托管代码,并且我尝试从 C# 使用它,但我不断收到 AccessViolationException。

是什么原因造成的?我该如何解决?

namespace FingerPrint {
    public unsafe partial class Form1 : Form {

        [DllImport("MyDll.dll")]
        public static extern int DoesExist();

        public unsafe Form1() {
            InitializeComponent();

            MessageBox.Show(DoesExist() + "");
        }
    }
}

I'm using a dll that contains unmanaged code for interacting with specific hardware, and I'm trying to use it from C#, but I keep getting an AccessViolationException.

What's causing it, and how can I fix it?

namespace FingerPrint {
    public unsafe partial class Form1 : Form {

        [DllImport("MyDll.dll")]
        public static extern int DoesExist();

        public unsafe Form1() {
            InitializeComponent();

            MessageBox.Show(DoesExist() + "");
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

眼睛会笑 2024-09-03 13:58:06

非托管代码的所有故障模式中大约 95% 都会产生访问冲突。您可以通过错误的 [DllImport] 声明来触发此类故障模式。但发布的DoesExist() 无法触发。

请联系 DLL 的供应商或作者以获得支持。如果你这么容易就失败了,他们应该可以轻松地重现错误并使用调试器及其源代码进行诊断。

为了完整起见,AccessViolation 的最典型原因是:

  • 非托管代码中的内存管理错误,导致堆损坏,
  • 不验证数据,导致空取消引用或缓冲区溢出,
  • 在调用支持函数时不检查失败返回错误代码

Roughly 95% of all failure modes for unmanaged code produce an access violation. You can trigger such a failure mode by getting the [DllImport] declaration wrong. But DoesExist() as posted cannot trigger one.

Contact the vendor or the author of the DLL for support. They should have little trouble reproducing the fault and diagnosing it with a debugger and their source code if you got it to fail so easily.

For completeness, the most typical causes of AccessViolation:

  • a memory management bug in the unmanaged code, causing heap corruption
  • not validating data, causing null dereferences or buffer overflows
  • not checking for failure return error codes when calling support functions
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文