Understanding LoadLibrary

A short guide to LoadLibrary and GetProcAddress in Windows.


Something that I have been asked about recently is dynamically loading functions from shared libraries (DLL's). This is a pretty simple thing to accomplish. I shall show you how to do this with a simple example.

Loading Libraries

The first thing that you need to know, is how to actually load the library. Depending on your project config, you will typically either use LoadLibraryA or LoadLibraryW (Either that, or you'll just use the LoadLibrary macro). Here I will use the ASCII version, Win32 functions with the 'W' suffix are used in Unicode projects. This example will show you how simple it is to load a library by loading our own library: foo.dll.

1// Load the library
2HMODULE fooModule = LoadLibraryA("foo.dll");

If you are familiar with the Win32 API's, then you will already know what HMODULE means, but for those who are new to this; HMODULE is simply the library's base address, which is used for getting function pointers later.

Freeing Libraries

The next important thing to remember, is to free libraries when you are finished to tell Windows that you no longer need to keep this library loaded. This is as simple as calling FreeLibrary(fooModule).

Loading Functions/Variables

Now, to the most exciting part, loading functions (or variables)!

To load a function from a shared library, we use the GetProcAddress function. The only arguments you need to provide to this are; the HMODULE that you are loading from and the name of the function or variable you wish to load. In this example, our library (foo.dll) will have an function called exampleFunction and it will return an int, but has no parameters.

1// First, we must define the function, it's arguments and return type.
2typedef int (*FN_exampleFunction)();
4// Then we can get the pointer to this function
5FN_exampleFunction exampleFunction = (FN_exampleFunction) GetProcAddress(fooModule, "exampleFunction");
7// Now we can call this function how we'd want.

Complete example

Here is a complete code example:

1// Define the function
2typedef int (* FN_exampleFunction)();
4int main() {
5    // First, load foo.dll
6    HMODULE foo = LoadLibraryA("foo.dll");
8    // Now we can load the function and call it
9    FN_exampleFunction exampleFunction = (FN_exampleFunction) GetProcAddress(foo, "exampleFunction");
10    int retValue = exampleFunction();
12    // Free the library before we close
13    FreeLibrary(foo);
15    // For this example, lets assume when retValue == 2, the program was a success
16    if (retValue == 2)
17        return 0;
18    return -1; // Non-zero exit code is an error

I hope this was helpful to you! And if you notice any problems with this, contact me please!