Abstract

This article presents a C++ solution for managing dynamic libraries (and entities imported from dynamic libraries).

The term “import” will henceforth designate the process of loading a dynamic library, and then obtain the address of some symbol (function or object) from that dynamic library, with a system call such as GetProcAddress or dlsym.

Even some experienced programmers might have unloaded a dynamic library once or twice in their career, and then spent time trying to understand why a pointer to an object, or to a function, out of the sudden refers to nothing but thin air. The C system APIs for managing dynamic libraries put the burden of keeping track of what dynamic libraries are in use on the programmer.

As many readers may already know, smart pointers can help reduce the burden of keeping track of malloc (or new) calls and matching them with free (and delete, respectively). In a similar manner, one can use a reference-counted pointer to help managing dynamic libraries. This article shows a way of implementing this in C++ code.

Although “dynamic library” is a term that is commonly used on the Windows platforms, in this article it equally designates shared libraries (or shared objects, as they are more commonly called by Unix programmers). For those readers that are new to the concept of dynamic library, I will briefly explain the idea in the first paragraph.

The design goals of the presented approach are:

  • Abstracting out the operating system specificities related to managing dynamic libraries;

  • Forbidding the early unloading of modules from the process’ memory, and thus prevent dangling pointers (that can point to either code or data);

  • Providing a mechanism for automatic loading (as soon as a function or object needs to be imported from a dynamic library) and unloading (as soon as there are no more imported functions or objects in use);

  • Managing objects created by factory methods inside the dynamic library.

The design stars a reference-counted smart pointer, and features guest appearances of Boost and Loki.