Loading of a C++ class from a shared library (Modern C++)

  • Modern C++ (from c++11): Use of smart pointers to store the classes retrieved from the libraries
  • Cross-platform: Works on UNIX (tested on Linux & MacOS) and Windows.
  • Generic enough to be used by a wide range of programs.
  • It requires no restart when you “load” or “unload” a shared library from an executable, because it isn’t statically linked.
  • The library’s content is not included in the binary, and therefore the developer doesn’t have to compile it each time (s)he wants to update the binary.
  • The developer is able to push further the separation of concerns, and to improve the overall reusability of the components.
  • We use a conditional preprocessor macro : #ifdef to only enter the condition if we are compiling on a specific platform. Here it may be Windows (WIN32), MacOS (__APPLE__), or Linux (__linux__). We can't exactly use the same code for both platforms because of the next point.
  • For Windows we have to include __declspec (dllexport) before the function prototype. More info on this here.
  • There is this extern "C" line, wrapping some C-like functions. It is in this part that we will set our entry points to load and unload the library class right into and from our "core" program. To know why we need it, we must understand how dynamic loading works.
  • Allocator entry point: function pointer of type allocClass & held by the variable allocFunc.
  • Deleter entry point: function pointer of type deleteClass & held by the variable deleteFunc.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store