-
Notifications
You must be signed in to change notification settings - Fork 2
/
dlclass.cpp
73 lines (59 loc) · 1.76 KB
/
dlclass.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
template <class T>
DLClass<T>::DLClass(std::string module_name) :
module(module_name){
shared = std::make_shared<shared_obj>();
}
template <class T>
DLClass<T>::~DLClass() {
//close_module();
}
template <class T>
void DLClass<T>::shared_obj::close_module() {
if(dll_handle) {
dlclose(dll_handle);
dll_handle = NULL;
}
if(create) create = NULL;
if(destroy) destroy = NULL;
}
template <class T>
bool DLClass<T>::shared_obj::open_module(std::string module) {
dll_handle = dlopen(module.c_str(), RTLD_LAZY);
if(!dll_handle) {
std::cerr << "Failed to open library: " << dlerror() << std::endl;
return false;
}
// Reset errors
dlerror();
create = (typename T::create_t*) dlsym(dll_handle, "create");
const char * err = dlerror();
if(err) {
std::cerr << "Failed to load create symbol: " << err << std::endl;
close_module();
return false;
}
destroy = (typename T::destroy_t*) dlsym(dll_handle, "destroy");
err = dlerror();
if(err) {
std::cerr << "Failed to load destroy symbol: " << err << std::endl;
close_module();
return false;
}
return true;
}
template <class T> template< typename... Args>
std::shared_ptr<T> DLClass<T>::make_obj(Args... args) {
if(!shared->create || !shared->destroy) {
if(!shared->open_module(module)) {
return std::shared_ptr<T>(NULL);
}
}
// auto create_args = ((T* (*)(Args...))create);
std::shared_ptr<shared_obj> my_shared = shared;
return std::shared_ptr<T>(shared->create(args...),
[my_shared](T* p){ my_shared->destroy(p); });
}
template <class T>
DLClass<T>::shared_obj::~shared_obj() {
close_module();
}