Implicit and Explicit DLL loading

Posted by on in Blogs




DLL could be loaded implicitly or explicitly. Another way is Static Linkage that allows placing all required functions to your program to avoid DLLs usage at all, but it is out of this post.
Implicit DLL loading is having your program to load DLL before main() called. You specify DLL's library name already when linking a program; it will work with that exact version of DLL and will not even start without.
Implicit load pros/contras:
+ Simple
+ Program will either start or not
- Longer loading
- Depends on exact DLL version
Explicit DLL loading allows loading DLL when only needed, like a plug-in. After DLL loaded you call its functions by known names and then unload.
Explicit load pros/contras:
+ Compatible with future DLL versions
+ Flexibility
- React delay
- DLL incompatibility could be discovered too late
Let us think that My.DLL has this function:
extern "C" __stdcall __declspec(dllexport) int DllFunction(void);

I will describe syntax later; here I just place minimal code for both DLL usage types.
Implicit.cpp:
extern "C" __stdcall __declspec(dllimport) int DllFunction(void);

int main() {

    return DllFunction();

}

Explicit.cpp:
#include <windows.h>

extern "C" __stdcall __declspec(dllimport) int DllFunction(void);

int main() {

    int res = 0;

    HINSTANCE dll_handle = LoadLibrary("My.DLL");

    FARPROC func_addr;

    typedef int (__stdcall * pfVoidRetInt)(void);

    pfVoidRetInt MyFunction;

    if (dll_handle) {

        func_addr = GetProcAddress(HMODULE(dll_handle), "_DllFunction");

        if (func_addr) {

            MyFunction = pfVoidRetInt (func_addr);

            res = MyFunction();

        }

        FreeLibrary(dll_handle);

    }

    return res;

}

I prefer 2nd variant though.


Comments

Check out more tips and tricks in this development video: