C ++ dynamically loads classes

I am still a little new to C ++, so I bear it with my weakness.

I want a user of my program to be able to add their own classes. I have an abstract Module class, and my application consists of a set of subclasses of Module .

Is it possible to be able to search for a specific directory and dynamically load subclasses of Module (added by the user)?

In Java, I could achieve this using the org.reflections API. I assume the C ++ equivalent uses DLLs. Maybe I'm wrong.

Thanks in advance.

+6
source share
1 answer

As far as I know, the C ++ compilation model does not have a direct direct way to β€œexport classes”. However, you can do this 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 this library and extract the create_module and free_module and dynamically add their function pointers 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 usual mechanism of the virtual destructor should work even in dynamically loaded libraries.

For instance:

 std::unique_ptr<Module> make_module(std::string const & s) { auto it = plugins.find(s); return { it == plugins.end() ? nullptr : it->second.first() }; } 
+5
source

Source: https://habr.com/ru/post/944760/


All Articles