“尝试读取或写入受保护的存储器”从 C++/CLI 包装器 dll 传递本机对象时出错

发布于 2024-11-29 19:31:14 字数 669 浏览 1 评论 0原文

我有一个带有接口的大型 C++ 项目。 我构建了一个 C++/CLI 包装器 dll 以便与项目进行通信。

它由托管类构建,每个托管类都保存对本机对象和函数包装器的引用。该项目有一个工厂方法,创建一个对象并将其作为抽象类返回,主对象继承(我们称之为 IObject)。

在 C++ 中调用工厂函数“createObject”时,一切正常。此外,在 C++/CLI 中,对象会返回并正常工作。但在 C# 中,在两个 DLL 都存在并且程序引用托管 DLL 后,当我到达托管 DLL 的“createObject”函数时,程序在运行时崩溃,并显示:

“System.AccessViolationException”类型的未处理异常 发生在wrapper.dll中

附加信息:尝试读取或写入受保护的内存。 这通常表明其他内存已损坏。

这看起来不像是一个封送问题,因为它应该只返回指向本机对象的指针。

我尝试创建返回一些结构和字符串的工厂函数,一切正常。

我认为可能会发生这种情况,因为工厂函数返回的抽象类对象(IObject)比对象本身(Object - 继承自它)小,因此该对象包含的数据比 IObject 应该包含的数据多。但这就是工厂模式的工作原理!我看不出还有什么办法。

提前致谢。

I have a big C++ project with an interface.
I built a C++/CLI wrapper dll in order to communicate with the project.

It is built of managed classes, each holding a reference to a native object and functions wrappers. The project has a factory method creating an object and returning it as an abstract class, the main object inherits (lets call it IObject).

When calling the factory function "createObject" in C++ everything works well. Also in C++/CLI the object is returned and work properly. But in C#, after both of the DLLs are present and the managed one is referenced by the program, when I get to the managed DLL's "createObject" function the program crashes at runtime, saying:

An unhandled exception of type 'System.AccessViolationException'
occurred in wrapper.dll

Additional information: Attempted to read or write protected memory.
This is often an indication that other memory is corrupt.

It doesn't seem like a marshaling issue, since it should only return a pointer to a native object.

I tried creating factory functions returning some structs and strings, and everything worked well.

I thought it might happen because the abstract class object (IObject) returned by the factory function is smaller than the object itself (Object - which inherits from it), so the object contains more data than the size of IObject should. But this is how factory patterns work! I see no other way.

Thanks in advance.

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

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

发布评论

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

评论(1

暖伴 2024-12-06 19:31:14

我的猜测是你的 C++ 代码中的某个地方有一个错误的指针。在C++中调用时,它不关心,但在C#中调用时,它更多地保护内存。

只是一个猜测,但希望它指向正确的方向。

My guess is that you have a bad pointer in your C++ code somewhere. When calling in C++, it doesn't care, but when calling in C#, it protects the memory more.

Just a guess, but hopefully it's pointing in the right direction.

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