30#ifndef _MBXMLUTILS_SHAREDLIBRARY_H_
31#define _MBXMLUTILS_SHAREDLIBRARY_H_
38# ifndef WIN32_LEAN_AND_MEAN
39# define WIN32_LEAN_AND_MEAN
48inline std::string getLastError() {
50 const char *err=dlerror();
53 return std::to_string(GetLastError());
59namespace MBXMLUtils::SharedLibrary {
62 using Handle =
void *;
64 using Handle = HMODULE;
67 using InitFuncType = int (*)();
70 inline T getSymbol(
const std::string &file,
const std::string &symbolName,
bool throwOnError=
true);
75inline Handle load(
const std::string &file,
bool global=
false) {
76 static std::map<std::string, Handle> library;
77 std::pair<std::map<std::string, Handle>::iterator,
bool> res=library.insert(std::pair<std::string, Handle>(file, NULL));
80 res.first->second=dlopen(file.c_str(), RTLD_NOW | (global ? RTLD_GLOBAL : RTLD_LOCAL) | RTLD_DEEPBIND | RTLD_NODELETE);
82 std::string fileWinSep=file;
83 std::replace(fileWinSep.begin(), fileWinSep.end(),
'/',
'\\');
84 res.first->second=LoadLibraryEx(fileWinSep.c_str(), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
86 if(!res.first->second)
87 throw std::runtime_error(
"Unable to load the library '"+file+
"': "+getLastError());
90 auto initFunc=getSymbol<InitFuncType>(file,
"MBXMLUtils_SharedLibrary_init",
false);
94 throw std::runtime_error(
"Unable to initialize the library '"+file+
"'.\n"
95 "The function 'MBXMLUtils_SharedLibrary_init' returned with error code "+std::to_string(ret)+
".");
98 return res.first->second;
104inline T getSymbol(
const std::string &file,
const std::string &symbolName,
bool throwOnError) {
107 void *addr=dlsym(h, symbolName.c_str());
109 void *addr=
reinterpret_cast<void*
>(GetProcAddress(h, symbolName.c_str()));
113 throw std::runtime_error(
"Unable to load the symbol '"+symbolName+
"' from library '"+
114 file+
"': "+getLastError());
118 return reinterpret_cast<T
>(
reinterpret_cast<size_t>(addr));