views:

242

answers:

3

Say I have class A and class B. B inherits from class A, and implements a few virtual functions. The only problem is that B is defined in a .dll. Right now, I have a function that returns an instance of class A, but it retrieves that from a static function in the .dll that returns an instance of class B. My plan is to call the created object, and hopefully, have the functions in the .dll executed instead of the functions defined in class A. For some reason, I keep getting restricted memory access errors. Is there something I don't understand that will keep this plan from working?

+1  A: 

C++ classes do not cross DLL boundaries well. The DLL and the EXE need to be built with the exact same compiler and version -- preferably together. This is because class implementation specifics, like vtbl layout/order as well as implementations of some standard library features (i.e. std::string differences) are non portable. Different compilers' name-mangling schemes are also non potable between compilers/versions. The only interface you can reliably expose outside a DLL boundary is a C interface.

Because I don't know the exact scenario here I can't be sure, but you are probably invoking some type of undefined behavior across the DLL boundary.

EDIT: It's also possible that the DLL got unloaded at some point resulting to a call to nonexistent code in B.

Billy ONeal
I am compiling the .dll myself, I'm also trying to avoid the name-mangling schemes by making sure the functions are declared to be c functions.
Jeff
Sounds like the problem isn't due to calling the virtual function then. If you post some code we might be able to give a better answer.
Billy ONeal
I guess calling the function isn't the problem, I've found that the error occurs when I try to instantiate a pointer that's a member of class B within one of the virtual functions.
Jeff
+1  A: 

See my other extensive question&answer on this subject - does it help? http://stackoverflow.com/questions/1564802/how-to-work-portably-with-c-class-hierarchies-dynamic-linked-libraries

Virgil
A: 

Did you try debugging it with the Visual Studio debugger?

Set the debugger to catch win32 exceptions by going to Debug menu->Exceptions and mark the checkbox next to Win32 exceptions under Thrown
Now activate your exe using F5. The crash should alert the debugger and you should be able to see the exact location of the access violation.

shoosh
Yes, and perhaps step through the disassembly for more clues.
Qwertie