Exporting a C++ class from a DLL

What about late-binding? As in loading
it with LoadLibrary() and
GetProcAddress() ? I’m used being able
to load the library at run time and it
would be great if you could do that
here.

So there are two ways to load the DLL. The first is to reference one or more symbols from the DLL (your classname, for example), supply an appropriate import .LIB and let the linker figure everything out.

The second is to explicitly load the DLL via LoadLibrary.

Either approach works fine for C-level function exports. You can either let the linker handle it or call GetProcAddress as you noted.

But when it comes to exported classes, typically only the first approach is used, i.e., implicitly link to the DLL. In this case the DLL is loaded at application start time, and the application fails to load if the DLL can’t be found.

If you want to link to a class defined in a DLL, and you want that DLL to be loaded dynamically, sometime after program initiation, you have two options:

  1. Create objects of the class using a special factory function, which internally will have to use (a tiny bit of) assembler to “hook up” newly created objects to their appropriate offsets. This has to be done at run-time AFTER the DLL has been loaded, obviously. A good explanation of this approach can be found here.

  2. Use a delay-load DLL.

All things considered… probably better to just go with implicit linking, in which case you definitely want to use the preprocessor technique shown above. In fact, if you create a new DLL in Visual Studio and choose the “export symbols” option these macros will be created for you.

Good luck…

Leave a Comment