[ACCEPTED]-Dynamically importing a C++ class from a DLL-import

Accepted answer
Score: 13

You need to add the following:

extern "C"

to avoid function 5 mangling.

you might consider writing two 4 simple C functions:

SomeClass* CreateObjectInstace()
    return new SomeClass();

void ReleaseObject(SomeClass* someClass)
   delete someClass;

By only using those functions 3 you can afterward add/change functionality 2 of your object creation/deletion. This is 1 sometimes called a Factory.

Score: 6

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

Thanks for your efforts 1 guys & girls

Score: 2

I normally declare an interface base class, use 5 this declaration in my application, then 4 use LoadLibrary, GetProcAddress to get the 3 factory function. The factor always returns 2 pointer of the interface type.

Here is a 1 practical example, exporting an MFC document/view from a DLL, dynamically loaded

Score: 2

dllexport/dllimport works, place it before 20 your class name in the header file and you're 19 good to go.

Typically you want to use dllexport 18 in the dll, and dllimport in the exe (but 17 you can just use dllexport everywhere and 16 it works, doing it 'right' makes it tinily 15 faster to load).

Obviously that is for link-time 14 compilation. You can use /delayload linker 13 directive to make it 'dynamic', but that's 12 probably not what you want from the subject 11 line.

If you truly want a LoadLibrary style 10 loading, you're going to have to wrap your 9 C++ functions with "extern C" wrappers. The 8 problem is because of name mangling, you 7 could type in the fully-mangled name and 6 it'd work.

The workarounds are generally 5 to provide a C function that returns a pointer 4 to the correct class - COM works this way, as 3 it exports 4 C functions from a dll that 2 are used to get the interface methods inside 1 the object in the dll.

Score: 2

Check out this question. Basically, there are two ways. You 6 can mark the class using _dllexport and 5 then link with the import library, and the 4 DLL will be loaded automatically. Or if 3 you want to load the DLL dynamically yourself, you 2 can use the factory function idea that @titanae 1 suggested

More Related questions