Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Dynamically load classes

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.

like image 794
Zyyk Savvins Avatar asked May 11 '13 09:05

Zyyk Savvins


1 Answers

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() };
}
like image 107
Kerrek SB Avatar answered Nov 05 '22 15:11

Kerrek SB