OpenAstra
 
Loading...
Searching...
No Matches
dynamicloader.hpp
1#ifndef DYNAMICLOADER_H
2#define DYNAMICLOADER_H
3
4#include <dlfcn.h>
5
6#include <string>
7
8#include "debugprint.hpp"
9
10
11class DynamicLoader
12{
13public:
14 DynamicLoader( const std::string& dynamic_object_path ) {
15 int FLAGS = RTLD_NOW | RTLD_GLOBAL;
16 // int FLAGS = RTLD_LAZY | RTLD_GLOBAL;
17 _lib_handle = dlopen( dynamic_object_path.c_str(), FLAGS );
18
19 if ( _lib_handle != nullptr )
20 { // Clear loader errors:
21 dlerror();
22 }
23 else
24 DebugPrint() << "Unable to load dynamic object: " << dynamic_object_path << " - '" << dlerror() << "'";
25 }
26
27 virtual ~DynamicLoader() {
28 if ( _lib_handle != nullptr )
29 {
30 if ( _lib_handle != nullptr )
31 dlclose( _lib_handle );
32 _lib_handle = nullptr;
33 }
34 }
35
36 template<typename T>
37 T getSymbol( const std::string& symbol_name ) {
38 return T( _getSymbol( symbol_name ) );
39 }
40
44 bool isLoaded() const {
45 return _lib_handle != nullptr;
46 }
47
48private:
49 void* _getSymbol( const std::string& symbol_name ) const {
50 if ( _lib_handle == nullptr )
51 {
52 DebugPrint() << "Cannot to load symbol'" << symbol_name << "' if the dynamic object is not open.";
53 return nullptr;
54 }
55
56 // clear errors...
57 dlerror();
58 void* ret = dlsym( _lib_handle, symbol_name.c_str());
59 if ( ret == NULL )
60 DebugPrint() << "Unable to load symbol'" << symbol_name << "'.";
61 return ret;
62 }
63
64 void* _lib_handle;
65
66};
67
68#endif // DYNAMICLOADER_H
Definition debugprint.hpp:10
bool isLoaded() const
check if the object has been loaded properly
Definition dynamicloader.hpp:44