What is the correct way to import a C++ class from a DLL? We're using Visual C++.
There's the dllexport/exports.def+LoadLibrary+GetProcAddress trifecta, but it doesn't work on C++ classes, only C functions. Is this due to C++ name-mangling? How do I make this work?
You need to add the following:
extern "C"
{
...
}
to avoid function mangling.
you might consider writing two simple C functions:
SomeClass* CreateObjectInstace()
{
return new SomeClass();
}
void ReleaseObject(SomeClass* someClass)
{
delete someClass;
}
By only using those functions you can afterward add/change functionality of your object creation/deletion. This is sometimes called a Factory.
Found the solution at http://www.codeproject.com/KB/DLL/XDllPt4.aspx
Thanks for your efforts guys & girls
I normally declare an interface base class, use this declaration in my application, then use LoadLibrary, GetProcAddress to get the factory function. The factor always returns pointer of the interface type.
Here is a practical example, exporting an MFC document/view from a DLL, dynamically loaded
Check out this question. Basically, there are two ways. You can mark the class using _dllexport and then link with the import library, and the DLL will be loaded automatically. Or if you want to load the DLL dynamically yourself, you can use the factory function idea that @titanae suggested
dllexport/dllimport works, place it before your class name in the header file and you're good to go.
Typically you want to use dllexport in the dll, and dllimport in the exe (but you can just use dllexport everywhere and it works, doing it 'right' makes it tinily faster to load).
Obviously that is for link-time compilation. You can use /delayload linker directive to make it 'dynamic', but that's probably not what you want from the subject line.
If you truly want a LoadLibrary style loading, you're going to have to wrap your C++ functions with "extern C" wrappers. The problem is because of name mangling, you could type in the fully-mangled name and it'd work.
The workarounds are generally to provide a C function that returns a pointer to the correct class - COM works this way, as it exports 4 C functions from a dll that are used to get the interface methods inside the object in the dll.