Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #ifndef LIBRARY_WRAPPER_HPP
- #define LIBRARY_WRAPPER_HPP
- #include <cstdlib>
- #include <dlfcn.h>
- template <class T> class LibraryWrapper: public T {
- private:
- static std::string name;
- static void* handle; // link to opened library
- protected:
- T* data; // actual data
- public:
- LibraryWrapper(const std::string libname) {
- if (LibraryWrapper<T>::handle == NULL) {
- std::string fullname = "./lib" + libname + ".so";
- LibraryWrapper<T>::handle = dlopen(fullname.c_str(), RTLD_LAZY);
- if (LibraryWrapper<T>::handle == NULL) {
- std::cout << dlerror() << std::endl;
- std::exit(EXIT_FAILURE);
- }
- LibraryWrapper<T>::name = libname;
- std::cout << "Handle loaded\n";
- }
- T* (*create)();
- std::string init = "create_" + LibraryWrapper<T>::name;
- create = (T* (*)())dlsym(LibraryWrapper<T>::handle, init.c_str());
- this->data = (T*)create();
- }
- ~LibraryWrapper() {
- void (*destroy)(T*);
- std::string fin = "destroy_" + LibraryWrapper<T>::name;
- destroy = (void (*)(T*))dlsym(LibraryWrapper<T>::handle, fin.c_str());
- destroy(this->data);
- }
- };
- template<class T> std::string LibraryWrapper<T>::name = "";
- template<class T> void* LibraryWrapper<T>::handle = NULL;
- #endif
Advertisement
Add Comment
Please, Sign In to add comment