Understanding LoadLibrary
Hello!
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.
// Load the library
HMODULE 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.
// First, we must define the function, it's arguments and return type.
typedef int (*FN_exampleFunction)();
// Then we can get the pointer to this function
FN_exampleFunction exampleFunction = (FN_exampleFunction) GetProcAddress(fooModule, "exampleFunction");
// Now we can call this function how we'd want.
Complete example
Here is a complete code example:
// Define the function
typedef int (* FN_exampleFunction)();
int main() {
// First, load foo.dll
HMODULE foo = LoadLibraryA("foo.dll");
// Now we can load the function and call it
FN_exampleFunction exampleFunction = (FN_exampleFunction) GetProcAddress(foo, "exampleFunction");
int retValue = exampleFunction();
// Free the library before we close
FreeLibrary(foo);
// For this example, lets assume when retValue == 2, the program was a success
if (retValue == 2)
return 0;
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!