00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012 #ifndef Reflex_SharedLibrary
00013 #define Reflex_SharedLibrary
00014
00015
00016 #ifdef _WIN32
00017 # include <windows.h>
00018 #else
00019 # include <dlfcn.h>
00020 # include <errno.h>
00021 #endif
00022
00023
00024 namespace Reflex {
00025
00026
00027
00028
00029
00030
00031
00032 class SharedLibrary {
00033 public:
00034 SharedLibrary(const std::string& libname);
00035
00036 bool Load();
00037
00038 bool Unload();
00039
00040 bool Symbol(const std::string& symname,
00041 void*& sym);
00042
00043 const std::string Error();
00044
00045 private:
00046
00047 #ifdef _WIN32
00048 HMODULE fHandle;
00049 #else
00050 void* fHandle;
00051 #endif
00052
00053 std::string fLibName;
00054 };
00055
00056 }
00057
00058
00059
00060 inline Reflex::SharedLibrary::SharedLibrary(const std::string& libname):
00061
00062 fHandle(0),
00063 fLibName(libname) {
00064 }
00065
00066
00067
00068 inline const std::string
00069 Reflex::SharedLibrary::Error() {
00070
00071 std::string errString = "";
00072 #ifdef _WIN32
00073 int error = ::GetLastError();
00074 LPVOID lpMessageBuffer;
00075 ::FormatMessage(
00076 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
00077 NULL,
00078 error,
00079 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
00080 (LPTSTR) &lpMessageBuffer,
00081 0,
00082 NULL);
00083 errString = (const char*) lpMessageBuffer;
00084
00085 ::LocalFree(lpMessageBuffer);
00086 #else
00087 errString = std::string(dlerror());
00088 #endif
00089 return errString;
00090 }
00091
00092
00093
00094 inline bool
00095 Reflex::SharedLibrary::Load() {
00096
00097
00098 #ifdef _WIN32
00099 ::SetErrorMode(0);
00100 fHandle = ::LoadLibrary(fLibName.c_str());
00101 #else
00102 fHandle = ::dlopen(fLibName.c_str(), RTLD_LAZY | RTLD_GLOBAL);
00103 #endif
00104
00105 if (!fHandle) {
00106 return false;
00107 } else { return true; }
00108 }
00109
00110
00111
00112 inline bool
00113 Reflex::SharedLibrary::Symbol(const std::string& symname,
00114 void*& sym) {
00115
00116
00117 if (fHandle) {
00118 #ifdef _WIN32
00119 sym = GetProcAddress(fHandle, symname.c_str());
00120 #else
00121 sym = dlsym(fHandle, symname.c_str());
00122 #endif
00123
00124 if (sym) {
00125 return true;
00126 }
00127 }
00128 return false;
00129 }
00130
00131
00132
00133 inline bool
00134 Reflex::SharedLibrary::Unload() {
00135
00136
00137 #ifdef _WIN32
00138
00139 if (FreeLibrary(fHandle) == 0) {
00140 return false;
00141 }
00142 #else
00143
00144 if (dlclose(fHandle) == -1) {
00145 return false;
00146 }
00147 #endif
00148 else { return true; }
00149 }
00150
00151
00152 #endif // Reflex_SharedLibrary