Dynamically importing a C++ class from a DLL

28,044

Solution 1

Found the solution at http://www.codeproject.com/KB/DLL/XDllPt4.aspx

Thanks for your efforts guys & girls

Solution 2

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.

Solution 3

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

Solution 4

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.

Solution 5

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

Share:
28,044
Sdig Sadok
Author by

Sdig Sadok

Entrepreneur, developer and all-around geek

Updated on August 07, 2022

Comments

  • Sdig Sadok
    Sdig Sadok almost 2 years

    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?

  • jrh
    jrh about 3 years
    This code allows you to create the class using a C interface, but note that all of the class's methods will still need to be loaded using GetProcAddress, which will still require name mangling or additional C functions (e.g., void SomeObject_SomeMethod(SomeClass* const thisPointer, const int someArg){thisPointer->SomeMethod(someArg);} for every method you use on the object.