Skip to content

Instantly share code, notes, and snippets.

@lukicdarkoo
Created April 15, 2021 12:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukicdarkoo/09e162c0ff32754e4d9f844a057c1b4d to your computer and use it in GitHub Desktop.
Save lukicdarkoo/09e162c0ff32754e4d9f844a057c1b4d to your computer and use it in GitHub Desktop.
Plugin System using `dlopen`
#include "PluginInterface.hpp"
#include <dlfcn.h>
#include <iostream>
typedef PluginInterface *(*creatorFunction)();
int main()
{
void *handle = dlopen("myplugin.so", RTLD_LAZY);
if (!handle)
{
fprintf(stderr, "dlopen failure: %s\n", dlerror());
exit(EXIT_FAILURE);
}
creatorFunction create = (creatorFunction)dlsym(handle, "create_plugin");
PluginInterface *plugin = (*create)();
plugin->method();
delete plugin;
dlclose(handle);
return 0;
}
all:
g++ -shared -fPIC MyPlugin.cpp -o myplugin.so
g++ main.cpp -o main -ldl
#include "PluginInterface.hpp"
#include <iostream>
class MyPlugin : public PluginInterface
{
public:
virtual void method() override;
};
void MyPlugin::method()
{
std::cout << "Method is called\n";
}
extern "C" PluginInterface* create_plugin()
{
return new MyPlugin();
}
class PluginInterface
{
public:
virtual void method() = 0;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment