Using Run-Time Dynamic Linking Program Example
You can use the same DLL in both load-time and run-time dynamic linking. The following example uses the LoadLibrary() function to get a handle to the Myputs DLL. If LoadLibrary() succeeds, the program uses the returned handle in the GetProcAddress() function to get the address of the DLL's myPuts function. After calling the DLL function, the program calls the FreeLibrary() function to unload the DLL. Because the program uses run-time dynamic linking, it is not necessary to link the module with an import library for the DLL. The following example illustrates an important difference between run-time and load-time dynamic linking. If the DLL is not available, the application using load-time dynamic linking must simply terminate. The run-time dynamic linking example, however, can respond to the error.
Create a new empty Win32 console application project. Give a suitable project name and change the project location if needed.
Then, add the source file and give it a suitable name.
Next, add the following source code.
// A simple program that uses LoadLibrary() and
// GetProcAddress() to access myPuts() from Myputs.dll.
typedef int (*MYPROC)(LPWSTR);
int wmain(int argc, WCHAR **argv)
BOOL fFreeResult, fRunTimeLinkSuccess = FALSE;
// Get a handle to the DLL module.
hinstLib = LoadLibrary(LMyTestDll.dll);
// If the handle is valid, try to get the function address.
if (hinstLib != NULL)
wprintf(LLoadLibrary() is OK!\n);
ProcAdd = (MYPROC) GetProcAddress(hinstLib, myPuts);
// If the function address is valid, call the function.
if (ProcAdd != NULL)
wprintf(LGetProcAddress() is fine!\n);
fRunTimeLinkSuccess = TRUE;
(ProcAdd) (LAnother message from executable lol!);
wprintf(LGetProcAddress() failed miserably, error %d\n, GetLastError());
// Free the DLL module.
fFreeResult = FreeLibrary(hinstLib);
wprintf(LLoadLibrary() failed miserably, error %d\n, GetLastError());
// If unable to call the DLL function, use an alternative.
wprintf(LFailed to call the DLL's function! Error %d\n, GetLastError());
Build the project. There should be no error because the LoadLibrary() happens during the run-time. Copy the previously created DLL, MyTestDll.dll into the project’s Debug folder.
Run the application project. The following sample output shows the application successfully 'imported' the DLL's function.