20.2.1 Sharing Objects Between Applications

By using dynamic-link libraries, applications can share certain types of objects, including code and resources. Sharing other types of objects, including data and file handles, is much more limited. This is because file handles and data are created in an application's private address space. Attempts to share file handles, or to share data (outside of dynamic data exchange, the clipboard, and the library's data segment) will lead to unpredictable results, and could be incompatible with future versions of Windows.

20.2.1.1 Sharing Code

If you are developing a family of applications, you may want to consider using one or more dynamic-link libraries. This saves memory when two or more applications that use a common set of DLL functions are running at the same time. With these libraries, multiple applications can share common routines that would be duplicated for each application if static-link libraries were used.

Suppose, for example, that you are creating two graphics applications, one a vector (draw) program and the other a bitmap (paint) application. A common requirement for both programs is the ability to import drawings created by other applications. For these applications, you could create dynamic-link libraries for each supported “foreign” file format that would convert it into an intermediate format. Your paint and draw applications could then convert this intermediate data into their own formats. The applications themselves would be required to contain only the code to convert from a single format to their own format. To support the importing of a new file type, you would simply develop a new library module and distribute it to the user, instead of modifying, recompiling, and distributing the application modules themselves.

20.2.1.2 Sharing Resources

Resources are read-only data objects that are bound into an executable file by Microsoft Windows Resource Compiler (RC). You can bind resources into an application's .EXE file, as well as into a library's .DLL file. Applications can share a dynamic-link library's resources; this saves memory when multiple applications are running. Windows has built-in support for eight resource types:

Accelerator tables

Bitmaps

Cursors

Dialog box templates

Fonts

Icons

Menu templates

String tables

In addition to using the standard Windows resources, you can create custom resources and install them in an executable file. For more information about resources, see Chapter 16, “More Memory Management.”

Any application can freely use resources that reside in a dynamic-link library. However, each application must explicitly request each resource object it requires. For example, if an application uses a menu resource called MainMenu in a library named MENULIB.DLL, it would have to contain code similar to the following:

HINSTANCE hLibrary;
HMENU  hMenu;

hLibrary = LoadLibrary("MENULIB.DLL");

hMenu = LoadMenu(hLibrary, "MainMenu");