src/utils/DynamicLibrary.h

00001 #ifndef HT_UTILS_DYNAMICLIBRARY_H
00002 #define HT_UTILS_DYNAMICLIBRARY_H
00003 
00004 #include <hightest/config.h>
00005 #include <utils/Error.h>
00006 #include <dlfcn.h>
00007 
00008 namespace ht {
00009     namespace utils {
00011         class LoadError : public BaseException {
00012         public:
00014         LoadError(const std::string &s) : BaseException(s) {}
00015         };
00016 
00017         template <typename TestFunction>
00018             void LoadFunction(const std::string & filename, 
00019                               const std::string & name, 
00020                               TestFunction &func)
00021         {
00022             std::string sofilename = filename + ".so";
00023             void * handle = dlopen(sofilename.c_str(), RTLD_LAZY);
00024             if (!handle)
00025                 handle = dlopen(filename.c_str(), RTLD_LAZY);
00026             if (!handle) {
00027                 throw LoadError(std::string("Cannot open library: ") + 
00028                                 dlerror());
00029             }
00030             union {
00031                 TestFunction function;
00032                 void * ptr;
00033             } Converter;
00034             Converter.ptr = dlsym(handle, name.c_str());
00035             const char * dlsym_error = dlerror();
00036             if (dlsym_error) {
00037                 dlclose(handle);
00038                 throw LoadError(std::string("Cannot load symbol " + name + ": ") + 
00039                                 dlsym_error);
00040             }
00041             func = Converter.function;
00042         }
00043         
00044     }
00045 }
00046 
00047 #endif
00048 

Generated on Thu Jan 3 15:26:45 2008 by  doxygen 1.5.2