|
| 1 | +#ifndef HSIM_PLUGIN_INCLUDED |
| 2 | +#define HSIM_PLUGIN_INCLUDED |
| 3 | + |
| 4 | +#include <stdexcept> |
| 5 | +#include <string> |
| 6 | + |
| 7 | +#include <dlfcn.h> |
| 8 | + |
| 9 | +#include "plugin_api.hh" |
| 10 | + |
| 11 | +namespace hsim { |
| 12 | + |
| 13 | +class Plugin final { |
| 14 | + public: |
| 15 | + Plugin(const std::string &pluginPath, const std::string &options = "") |
| 16 | + : m_pluginName{pluginPath}, m_options{options} { |
| 17 | + m_dlhandle = dlopen(pluginPath.c_str(), RTLD_NOW); |
| 18 | + if (m_dlhandle == nullptr) { |
| 19 | + std::string dlErrorMsg = dlerror(); |
| 20 | + std::string fullErrorMsg = "Unable to load plugin: " + pluginPath + |
| 21 | + ". Error: " + dlErrorMsg; |
| 22 | + throw std::runtime_error(fullErrorMsg); |
| 23 | + } |
| 24 | + |
| 25 | + auto loadFunc = reinterpret_cast<LoadFunc>( |
| 26 | + dlsym(m_dlhandle, kLoadFuncName.c_str())); |
| 27 | + if (loadFunc == nullptr) { |
| 28 | + std::string dlErrorMsg = dlerror(); |
| 29 | + std::string fullErrorMsg = |
| 30 | + "Unable to load : " + pluginPath + ". Error: " + dlErrorMsg; |
| 31 | + throw std::runtime_error(fullErrorMsg); |
| 32 | + } |
| 33 | + |
| 34 | + LoadablePlugin plugin = loadFunc(options.c_str()); |
| 35 | + m_pluginMem = plugin.pluginMem; |
| 36 | + m_notify = plugin.notify; |
| 37 | + m_unload = plugin.unload; |
| 38 | + } |
| 39 | + |
| 40 | + ~Plugin() { |
| 41 | + m_unload(m_pluginMem); |
| 42 | + |
| 43 | + dlclose(m_dlhandle); |
| 44 | + } |
| 45 | + |
| 46 | + void notify() { m_notify(m_pluginMem); } |
| 47 | + |
| 48 | + private: |
| 49 | + std::string m_pluginName; |
| 50 | + std::string m_options; |
| 51 | + |
| 52 | + void *m_dlhandle; |
| 53 | + void *m_pluginMem; |
| 54 | + NotifyFunc m_notify; |
| 55 | + UnloadFunc m_unload; |
| 56 | +}; |
| 57 | + |
| 58 | +} // namespace hsim |
| 59 | + |
| 60 | +#endif // HSIM_PLUGIN_INCLUDED |
0 commit comments