Using Dynamically Loaded Shared Objects

One more way to use shared libraries is to load them dynamically at runtime, not as libraries linked and loaded automatically, but as entirely separate modules you explicitly load using the dlopen interface. You might want to use the dl (dynamic loading) interface because it provides greater flexibility for both the programmer and end user, and because the dl interface is a more general solution.

Suppose, for example, you are writing the next killer graphics manipulation and creation program. Within your application, you handle graphical data in a proprietary but easy-touse way. However, you want to be able to import and export from and to any of the literally hundreds of available graphics file formats. One way to achieve this would be to write one or more libraries, of the sort discussed in this chapter, to handle importing and exporting from and to the various formats. Although it is a modular approach, each library change would require recompilation, as would the addition of new formats.

The dl interface enables a different approach: designing a generic, format-neutral interface for reading, writing, and manipulating graphics files of any format. To add a new or modified graphics format to your application, you simply write a new module to deal with that format and make your application aware that it exists, perhaps by modifying a configuration file or placing the new module in a predefined directory (the plug-ins that augment the Netscape Web browser’s capabilities use a variation of this approach).

  To extend your application’s capabilities, users simply need to obtain new modules (or plugins); they (or you) do not need to recompile your application, only to edit a configuration file or copy the module to a preset directory. Existing code in your application loads the new modules and, voilá, you can import and export a new graphic format. The dl interface (which is itself implemented as a library, libdl), contains functions to load, search, and unload shared objects.

  To use these functions, include <dlfcn.h> in your source code and link against libdl using -ldl in your compilation command or make file. Notice that you don’t have to link against the library you want to use. Even though you use a standard shared library, you do not use it the normal way. The linker never knows about shared objects and, in fact, the modules do not even need to exist when you build the application.

Posted on: 18/12/2009

If you want to leave a comment please Login or Register