开发者

"Attempted to read or write protected memory" error when passing a native object from C++/CLI wrapper dll

开发者 https://www.devze.com 2023-03-28 09:48 出处:网络
I have a big C++ project with an interface. I built a C++/CLI wrapper dll in order to communicate with the project.

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:

开发者_JAVA技巧

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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消