Glocke

LibraryWrapper.hpp

Jan 8th, 2013
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.47 KB | None | 0 0
  1. #ifndef LIBRARY_WRAPPER_HPP
  2. #define LIBRARY_WRAPPER_HPP
  3.  
  4. #include <cstdlib>
  5. #include <dlfcn.h>
  6.  
  7. template <class T> class LibraryWrapper: public T {
  8.  
  9.     private:
  10.         static std::string name;
  11.         static void* handle; // link to opened library
  12.  
  13.     protected:
  14.         T* data; // actual data
  15.  
  16.     public:
  17.         LibraryWrapper(const std::string libname) {
  18.             if (LibraryWrapper<T>::handle == NULL) {
  19.                 std::string fullname = "./lib" + libname + ".so";
  20.                 LibraryWrapper<T>::handle = dlopen(fullname.c_str(), RTLD_LAZY);
  21.                 if (LibraryWrapper<T>::handle == NULL) {
  22.                     std::cout << dlerror() << std::endl;
  23.                     std::exit(EXIT_FAILURE);
  24.                 }
  25.                 LibraryWrapper<T>::name = libname;
  26.                 std::cout << "Handle loaded\n";
  27.             }
  28.             T* (*create)();
  29.             std::string init = "create_" + LibraryWrapper<T>::name;
  30.             create = (T* (*)())dlsym(LibraryWrapper<T>::handle, init.c_str());
  31.             this->data = (T*)create();
  32.         }
  33.         ~LibraryWrapper() {
  34.             void (*destroy)(T*);
  35.             std::string fin = "destroy_" + LibraryWrapper<T>::name;
  36.             destroy = (void (*)(T*))dlsym(LibraryWrapper<T>::handle, fin.c_str());
  37.             destroy(this->data);
  38.         }
  39.  
  40. };
  41.  
  42. template<class T> std::string LibraryWrapper<T>::name = "";
  43. template<class T> void* LibraryWrapper<T>::handle = NULL;
  44.  
  45. #endif
Advertisement
Add Comment
Please, Sign In to add comment