DYNAMIC LINKING WITHOUT IMPORTS

Rather than have Windows perform dynamic linking when your program is first loaded into memory, you can link a program with a library module while the program is running. We used this technique in Chapter 15 when we had to call the DeviceMode function in a printer driver module.

For instance, you would normally call the Rectangle function like this:

Rectangle (hdc, xLeft, yTop, xRight, yBottom) ;

You can also call Rectangle by first defining two variables:

HANDLE hLibrary ;

FARPROC lpfnRectangle ;

Now you set hLibrary to the handle of the library and lpfnRectangle to the address of the Rectangle function:

hLibrary = LoadLibrary ("GDI.EXE") ;

lpfnRectangle = GetProcAddress (hLibrary, MAKEINTRESOURCE (27)) ;

The LoadLibrary function returns an MS-DOS error code (less than 32) if the library file can't be found. In GetProcAddress, the second parameter is a number (27) that you convert to a far pointer to a string by setting the segment address equal to 0; 27 is the ordinal number of Rectangle obtained from the EXEHDR listing of GDI.EXE. Now you can call the function and then free the library:

(*lpfnRectangle) (hdc, xLeft, yTop, xRight, yBottom) ;

FreeLibrary (hLibrary) ;

For libraries in which the module definition file doesn't define ordinals for the exported functions, you can use the function name in the GetProcAddress call:

lpfnFunction = GetProcAddress (hLibrary, "FunctionName") ;

Don't use this method for linking to modules that use ordinal numbers for the exported functions. The names of the functions in a library remain resident in memory only if the module definition file doesn't include ordinals or if the keyword RESIDENTNAME is used with the functions in the EXPORTS statement.

Although this technique doesn't make much sense for the Rectangle function, it will definitely come in handy. You need to use it when you don't know the name of the library module until run time, as is the case with the DeviceMode function in the printer drivers.

The code above uses the LoadLibrary and FreeLibrary functions. Windows maintains ”reference counts“ for all library modules. LoadLibrary causes the reference count to be incremented. The reference count is also incremented when Windows loads any program that uses the library. FreeLibrary causes the reference count to be decremented, as does the termination of an instance of a program that uses this library. When the reference count is 0, Windows can discard the library from memory, because the library is no longer needed.