Example (_loadmod -- Load DLL) (Windows)

In this example, _loadmod loads the DLL mark and gets the address of the function PLUS within the DLL. It then calls that function, which adds two integers passed to it.

The types FARPROC and HMODULE are required to use the Win32 GetProcAddress API, and are defined by including the <windows.h> header file.

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
   *********************************************************************/
}