Visual C++ - Exporting functions in DLL and Dynamic Binding - Accessing by loading the DLL at run-time
Exporting functions in DLL and accessing by loading the DLL at run-time
Most libraries are written as a DLL application so that it can be shared across multiple client applications. I have given the sample code and download link for creating and testing a DLL server and client. The client application will dynamically load the DLL and get the procedure address and call the function. This is called dynamic binding. This would be an example for late binding also.
Creating a Test Server DLL application using Visual Studio
From Visual Studio 2008, use Visual C++ and Win32 and Select Win32 Project as shown below in the screen shot.
In the second page Application Settings, Make sure DLL radio button is selected to create TestServer DLL application.
Sample code for the server application to export a function
extern "C" __declspec(dllexport) bool GetWelcomeMessage(char *buf, int len)
if(buf != NULL && len > 48)
strcpy(buf, "Welcome Message From My First DLL function\n");
Output from Server DLL application
- TestServer.Lib - This file is used for static binding and not required if you are dynamically load the DLL.
- TestServer.DLL - This DLL is required at the run time while testing the client application. If you can place the DLL in the system path or in your client application working folder, then it is good enough for loading the DLL at run time
Steps for invoking a function by dynamically loading the DLL
- Declare the function pointer variable, can be a typedef. In this example, look for typedef bool (*GW)(char *buf, int len);
- Load the DLL using LoadLibrary call by passing the name of the DLL. The DLL needs to be in the system path or in the current directory. Alternatively you can specify the absolute or relative path.
- Get the procedure address for by passing the function name "GetWelcomeMessage" to the call GetProcAddress and assign the address to the function pointer variable.
- Invoke the function using function pointer and get the result.
- You do not need to link the TestServer.Lib in your client application.
- You must make the dll export function in the server as extern "C". Otherwise your GetProcAddress will return a NULL pointer.
Sample code for the client application to import a function
//__declspec(dllimport) bool GetWelcomeMessage(char *buf, int len); // used for static binding
typedef bool (*GW)(char *buf, int len);
HMODULE hModule = LoadLibrary(TEXT("TestServer.DLL"));
GW GetWelcomeMessage = (GW) GetProcAddress(hModule, "GetWelcomeMessage");
if(GetWelcomeMessage(buf, 128) == true)
std::cout << buf;
The code will produce the following output.
Welcome Message From My First DLL function
Click here to download the .ZIP file that has both client and server code for testing the DLL with dynamic binding.