30 #ifndef _MBXMLUTILS_SHAREDLIBRARY_H_
31 #define _MBXMLUTILS_SHAREDLIBRARY_H_
45 inline std::string getLastError() {
47 const char *err=dlerror();
50 return std::to_string(GetLastError());
56 namespace MBXMLUtils {
57 namespace SharedLibrary {
62 typedef HMODULE Handle;
65 typedef int (*InitFuncType)();
68 inline T getSymbol(
const std::string &file,
const std::string &symbolName,
bool throwOnError=
true);
73 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 InitFuncType 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));