.net - AccessViolation when interacting with native DLL for the first time
This is a little bit of a weird one, and my first foray into the world of .net so I'm hoping that I'm missing something fundamental :) Background:
I have a native/Qt c++ DL开发者_如何学JAVAL that I am wrapping for use in .NET, C# in this case. I have a Qt app that uses this DLL successfully, without memory leaks, etc. I have created a c++/CLI wrapper for this library and I can call into the native code through it successfully. However, I've noticed that depending on how I first interact with the managed DLL (and hence the native DLL), I see AccessViolation exceptions.
If I allocate an object out of the native DLL on the process (not .net) heap first, everything works as expected. But if I interact with an object from the native DLL by creating it on the stack, then subsequently allocate a native object on the heap, I later get AccessViolation exceptions in unrelated native DLL code. In fact, I only have to allocate the native object (and never reference it again) to see these errors.
The stack vs. heap issue may be a red herring of course, but it's 100% reproducible so seems like at least a good lead to hunt down. Any tips? Thanks!
How are you allocating things on the heap?
If you're allocating managed objects (gcnew
etc) and then passing those to unmanaged code, or simply passing pointers to existing managed objects into unmanaged code, then the garbage collector comes along and collects or relocates them. This causes your unmanaged code to have garbage pointers, hence (most probably) the access violation
We'd almost definitely need to see a code snippet in order to give much more help. Cheers
I agree with Orion Edwards, it most likely is a GC issue. To possibly help resolve it, you would need to "pin" the object so the GC doesn't collect it. This has its pitfalls, so be careful.
See this article for more info:
Copying and Pinning
Pinning temporarily locks the data in its current memory location, thus keeping it from being relocated by the common language runtime's garbage collector. The marshaler pins data to reduce the overhead of copying and enhance performance. The type of the data determines whether it is copied or pinned during the marshaling process.
精彩评论