30 #ifndef _MBXMLUTILS_SHAREDLIBRARY_H_
31 #define _MBXMLUTILS_SHAREDLIBRARY_H_
38 # define WIN32_LEAN_AND_MEAN
46 inline std::string getLastError() {
48 const char *err=dlerror();
51 return std::to_string(GetLastError());
57 namespace MBXMLUtils::SharedLibrary {
60 using Handle =
void *;
62 using Handle = HMODULE;
65 using InitFuncType = int (*)();
68 inline T getSymbol(
const std::string &file,
const std::string &symbolName,
bool throwOnError=
true);
73 inline Handle load(
const std::string &file,
bool global=
false) {
74 static std::map<std::string, Handle> library;
75 std::pair<std::map<std::string, Handle>::iterator,
bool> res=library.insert(std::pair<std::string, Handle>(file, NULL));
78 res.first->second=dlopen(file.c_str(), RTLD_NOW | (global ? RTLD_GLOBAL : RTLD_LOCAL) | RTLD_DEEPBIND | RTLD_NODELETE);
80 std::string fileWinSep=file;
81 std::replace(fileWinSep.begin(), fileWinSep.end(),
'/',
'\\');
82 res.first->second=LoadLibraryEx(fileWinSep.c_str(), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
84 if(!res.first->second)
85 throw std::runtime_error(
"Unable to load the library '"+file+
"': "+getLastError());
88 auto initFunc=getSymbol<InitFuncType>(file,
"MBXMLUtils_SharedLibrary_init",
false);
92 throw std::runtime_error(
"Unable to initialize the library '"+file+
"'.\n"
93 "The function 'MBXMLUtils_SharedLibrary_init' returned with error code "+std::to_string(ret)+
".");
96 return res.first->second;
102 inline T getSymbol(
const std::string &file,
const std::string &symbolName,
bool throwOnError) {
105 void *addr=dlsym(h, symbolName.c_str());
107 void *addr=
reinterpret_cast<void*
>(GetProcAddress(h, symbolName.c_str()));
111 throw std::runtime_error(
"Unable to load the symbol '"+symbolName+
"' from library '"+
112 file+
"': "+getLastError());
116 return reinterpret_cast<T
>(
reinterpret_cast<size_t>(addr));