Im still a bit new to C++, so bear with my noobiness.
What I want is to be able to allow the user of my program to be able to add his own classes. I have an abstract class Module
, and my application consists of a set of subclasses of Module
.
Is it possible to be able to search a particular directory and dynamically load subclasses of Module
(added by the user) ?
In Java I could achieve this using the org.reflections API. I'm guessing the C++ equivalent is using DLLs. I may be wrong.
Thanks in advance.
To my knowledge the C++ compilation model doesn't have an explicit, direct way of "exporting classes". However, you should be able to do it with a simple C-interface:
#include "MyModule.h"
// class MyModule inherits Module
extern "C" Module * create_module() { return new MyModule; }
extern "C" void free_module(Module * p) { delete p; }
Now you can dynamically load that library and retrieve the functions create_module
and free_module
, and add their function pointers dynamically to your system:
std::map<std::string, std::pair<Module * (*)(), void(*)(Module *)> plugins;
plugins["MyClass"] = std::make_pair(..., ...); // the dynamically resolved
// function addresses
In fact, you probably don't even need the destroyer function, since the ordinary virtual destructor machinery should work even in dynamically loaded libraries.
For example:
std::unique_ptr<Module> make_module(std::string const & s)
{
auto it = plugins.find(s);
return { it == plugins.end() ? nullptr : it->second.first() };
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With