Created
April 15, 2021 12:24
-
-
Save lukicdarkoo/09e162c0ff32754e4d9f844a057c1b4d to your computer and use it in GitHub Desktop.
Plugin System using `dlopen`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
all: | |
g++ -shared -fPIC MyPlugin.cpp -o myplugin.so | |
g++ main.cpp -o main -ldl |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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(); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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