Snap! Websites
An Open Source CMS System in C++
The following are 3 files you can use to create this example (see tar ball attachment below.) The original code comes from Aaron Isotton, although his example was not a true C++ sample... it would not use a global variable to auto-register the plug-in. Instead he would load a symbol. It is licensed under the GPL.
The first one (main.cpp) includes the code used to load and unload the plugin.
#include <iostream> #include <dlfcn.h> int main() { std::cout << "C++ dlopen demo" << std::endl << std::endl; // open the library std::cout << "Opening plugin.so..." << std::endl; void* handle = dlopen("./plugin.so", RTLD_LAZY); if (!handle) { std::cerr << "Cannot open plugin: " << dlerror() << std::endl; return 1; } // close the plugin std::cout << "Closing plugin..." << std::endl; dlclose(handle); std::cout << "PlugIn closed..." << std::endl; return 0; }
The second one (plugin.cpp) is a test module showing that a global C++ object will be created when loaded from a .so file.
#include <iostream> class PlugIn { public: PlugIn() { std::cout << " - Loaded PlugIn!!!" << std::endl; } ~PlugIn() { std::cout << " - Destroying PlugIn..." << std::endl; } }; // Global variable representing the plug-in PlugIn plugin;
Finally, you need to compile and link all of that with the following Makefile;
cpp-module: main.cpp plugin.so $(CXX) $(CXXFLAGS) -o cpp-module main.cpp -ldl plugin.so: plugin.cpp $(CXX) $(CXXFLAGS) -fPIC -shared -o plugin.so plugin.cpp clean: rm -f cpp-module plugin.so .PHONY: clean
Note that the plugin.so is created using the -shared flag and not linked in main.cpp. If you return before the dlopen(), you will never see the plugin.so messages printed.
An important note about the functionality: in our real version the C++ global variable has to be a factory and not the actual plug-in object. This is important to allow for proper allocation and registration. More or less, constructors cannot exactly do whatever they want.
Attachment | Size |
---|---|
cpp-module.tar_.gz | 13.07 KB |
Snap! Websites
An Open Source CMS System in C++