This example loads the DLL mark with _loadmod, and uses the API GetProcAddress to get the address of the function dor from within the DLL. It then calls that function, which multiplies two integers passed to it. When the function and DLL are no longer needed, the program frees the DLL module. The types HMODULE and FARPROC are defined by including <windows.h>.
Note: To run this program, you must first create mark.dll. Copy the code for the PLUS function into a file called mark.c, and the code for the .DEF file into mark.def. Eliminate the comments from these two files. Compile the example.
You can then run the example.
#include <windows.h> #include <stdio.h> #include <stdlib.h>
typedef (_Optlink *fptr)(int, int);
int main(void) {
int x = 4, y = 7; unsigned long handle; char *modname = "MARK"; /* DLL name */ char *fname = "PLUS"; /* function name */ fptr faddr; /* pointer to function */
/* dynamically load the 'mark' DLL */
if (_loadmod(modname, &handle)) {
printf("Error loading module %s\n", modname);
return EXIT_FAILURE;
}
/* get function address from DLL */
faddr = (fptr)GetProcAddress((HMODULE)handle, fname);
if (NULL != faddr) {
printf("Calling the function from the %s DLL to add %d and %d\n",
modname, x, y);
printf("The result from the function call is %d\n", faddr(x, y));
}
else {
DWORD rc = GetLastError();
printf("Error locating address of function %s, rc=%d\n", fname, rc);
_freemod(handle);
return EXIT_FAILURE;
}
if (_freemod(handle)) {
printf("Error in freeing the %s DLL module\n", modname);
return EXIT_FAILURE;
}
printf("Reference to the %s DLL module has been freed\n", modname);
/********************************************************************
The output should be:
Calling the function from MARK DLL to add 4 and 7
The result of the function call is 11
Reference to the MARK DLL module has been freed
********************************************************************/
}