bigsnitch/addonhandler.cpp
2020-09-10 21:26:41 +02:00

66 lines
1.6 KiB
C++

#include "addonhandler.h"
#include <dlfcn.h>
AddonHandler::AddonHandler()
{
}
std::optional<std::string> AddonHandler::load(std::filesystem::path path)
{
// load library
void* lib = dlopen(path.c_str(), RTLD_LAZY);
if(!lib) {
qDebug() << "addon " << path.c_str() << " not loaded!";
return std::nullopt;
}
auto get_name = reinterpret_cast<const char*(*)()>(dlsym(lib, "get_name"));
std::string name;
try {
get_name();
} catch (...) {
return std::nullopt;
}
auto initialize = reinterpret_cast<const char*(*)()>(dlsym(lib, "initialize"));
try {
if(initialize) {
initialize();
}
} catch (...) {
return std::nullopt;
}
on_request.append(name, dlsym(lib, "on_request"));
on_response.append(name, dlsym(lib, "on_response"));
loaded_addon_paths.insert(std::make_pair(name, path));
loaded_addon_libs.insert(std::make_pair(name, lib));
return name;
}
void AddonHandler::unload(std::string name)
{
on_request.remove(name);
on_response.remove(name);
void* lib = loaded_addon_libs.find(name)->second;
auto deinitialize = reinterpret_cast<const char*(*)()>(dlsym(lib, "initialize"));
try {
if(deinitialize) {
deinitialize();
}
} catch (...) {
qDebug() << "deinitialize failed";
}
}
bool AddonHandler::isLoaded(std::string name)
{
return loaded_addon_libs.count(name);
}
std::map<std::string, std::filesystem::path> AddonHandler::loadedAddons()
{
return std::map<std::string, std::filesystem::path>();
}