7 #ifndef _XSI_SHARED_LIB_H
8 #define _XSI_SHARED_LIB_H
24 typedef HINSTANCE handle_type;
26 typedef void* handle_type;
28 typedef void* symbol_type;
30 SharedLibrary() : _lib(0), _retain(false) { }
31 ~SharedLibrary() { unload(); }
32 operator bool()
const {
return (_lib != 0); }
33 bool loaded()
const {
return (_lib != 0); }
34 handle_type handle()
const {
return _lib; }
35 const std::string& path()
const {
return _path; }
36 const std::string& error()
const {
return _err; }
37 bool load(
const std::string& path)
44 _err =
"Failed to load shared library. "
45 "Path of the shared library is not specified.";
49 bool ok = load_impl(path, msg);
54 _err =
"Failed to load shared library \"" + path +
60 bool load_impl(
const std::string& path, std::string& errmsg)
65 _lib = LoadLibrary(path.c_str());
67 translate_error_message(GetLastError(), errmsg);
71 _lib = dlopen(path.c_str(), RTLD_LAZY | RTLD_GLOBAL);
72 char* err = dlerror();
101 bool getsymbol(
const std::string& name, symbol_type& sym)
107 msg =
"The shared library is not loaded.";
112 sym = (
void*) GetProcAddress(_lib, name.c_str());
114 translate_error_message(GetLastError(), msg);
119 sym = (
void*) dlsym(_lib, name.c_str());
120 char* err = dlerror();
131 _err =
"Failed to obtain symbol \"" + name +
132 "\" from shared library. " + msg;
138 symbol_type getfunction(
const std::string& name)
140 symbol_type sym = NULL;
141 return getsymbol(name, sym) ? sym : NULL;
146 SharedLibrary(
const SharedLibrary&);
147 const SharedLibrary& operator=(
const SharedLibrary&);
150 static void translate_error_message(DWORD errid, std::string& msg)
153 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
154 FORMAT_MESSAGE_FROM_SYSTEM |
155 FORMAT_MESSAGE_IGNORE_INSERTS,
158 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
164 msg =
reinterpret_cast<char*
>(bufptr);
169 static const std::string& library_suffix()
171 static const std::string s =
".dll";
175 static const std::string& library_suffix()
177 static const std::string s =
".so";
190 #endif // _XSI_SHARED_LIB_H