Wednesday, June 24, 2009

Resource Management Across DLL Boundaries

Resource management across DLL boundaries in C++ is tricky. Here are the basic rules used in Boost.Extension:

  1. Anything allocated inside the DLL must be deallocated before the DLL is released. This means that if you pass a std::map into the DLL and modify it, you must delete (or at least clear()) the std::map before releasing the DLL.
  2. In order to use an interface across the DLL boundary, you basically have to guarantee that both the DLL and main executable were compiled with the same options - this is, for me, the primary weakness of C++ with DLLs.
  3. RTTI does not always function as expected across DLL boundaries. Check out the type_info classes to see how I deal with that.
  4. Always use virtual destructors for your interfaces - then you can safely delete them from the main binary or in the DLL.
It took a whole lot of trial and error to get this to work on different platforms.