如何检测来自非托管 dll 的哪个回调会导致受保护的内存异常?

发布于 2024-08-26 20:28:29 字数 96 浏览 9 评论 0原文

我收到受保护的内存异常,但我如何知道哪个调用导致了它,以及为什么回调函数已移动?对非托管代码的所有调用都在与回调函数相同的类中完成,因此我认为地址不应更改,或者我在这里完全错了?

I get a protected memory exception, but how can I know which call caused it, and why the callback function has moved? All the calls to unmanaged code are done in the same class as the callback functions, so I suppose that the addresses should not change, or am I totally wrong here?

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

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

发布评论

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

评论(1

一城柳絮吹成雪 2024-09-02 20:28:29

为了使本机代码回调到托管代码,您需要一个回调委托(只要我们不讨论 COM 互操作)。最常见的错误原因是回调委托在最后一次回调发生之前被垃圾回收。回调目标在哪个类中定义并不重要,但保持委托处于活动状态至关重要。

只需指定方法名称并让 C# 编译器为您创建临时委托的能力使此错误更加常见。即,

SetCallback(MyCallbackMethod);  // No good since you can't keep reference to delegate

_callback = MyCallbackMethod;   // Create delegate explicitly and store reference at class level
SetCallback(_callback);

可以启用“托管调试助手”来帮助您找到此类错误。

For native code to call back into managed code you need a callback delegate (as long as we're not talking COM interop). And the most common reason for errors is that the callback delegate is garbage collected before the last callback occurs. It doesn't matter which class the callback target is defined in, but to keep the delegate alive is critical.

The ability to just specify the method name and let the C# compiler create a temporary delegate for you makes this error even more common. I.e. instead of

SetCallback(MyCallbackMethod);  // No good since you can't keep reference to delegate

do this

_callback = MyCallbackMethod;   // Create delegate explicitly and store reference at class level
SetCallback(_callback);

You can enable "managed debug assistants" to help you find this type of bug.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文