/src/behaviortreecpp/src/shared_library_UNIX.cpp
Line | Count | Source |
1 | | #include "behaviortree_cpp/exceptions.h" |
2 | | #include "behaviortree_cpp/utils/shared_library.h" |
3 | | |
4 | | #include <mutex> |
5 | | #include <string> |
6 | | |
7 | | #include <dlfcn.h> |
8 | | |
9 | | namespace BT |
10 | | { |
11 | 0 | SharedLibrary::SharedLibrary() = default; |
12 | | |
13 | | void SharedLibrary::load(const std::string& path, int) |
14 | 0 | { |
15 | 0 | const std::unique_lock<std::mutex> lock(_mutex); |
16 | |
|
17 | 0 | if(_handle != nullptr) |
18 | 0 | { |
19 | 0 | throw RuntimeError("Library already loaded: " + path); |
20 | 0 | } |
21 | | |
22 | 0 | _handle = dlopen(path.c_str(), RTLD_NOW | RTLD_GLOBAL); |
23 | 0 | if(_handle == nullptr) |
24 | 0 | { |
25 | 0 | const char* err = dlerror(); |
26 | 0 | throw RuntimeError("Could not load library: " + |
27 | 0 | (err != nullptr ? std::string(err) : path)); |
28 | 0 | } |
29 | 0 | _path = path; |
30 | 0 | } |
31 | | |
32 | | void SharedLibrary::unload() |
33 | 0 | { |
34 | 0 | const std::unique_lock<std::mutex> lock(_mutex); |
35 | |
|
36 | 0 | if(_handle != nullptr) |
37 | 0 | { |
38 | 0 | dlclose(_handle); |
39 | 0 | _handle = nullptr; |
40 | 0 | } |
41 | 0 | } |
42 | | |
43 | | bool SharedLibrary::isLoaded() const |
44 | 0 | { |
45 | 0 | return _handle != nullptr; |
46 | 0 | } |
47 | | |
48 | | void* SharedLibrary::findSymbol(const std::string& name) |
49 | 0 | { |
50 | 0 | const std::unique_lock<std::mutex> lock(_mutex); |
51 | |
|
52 | 0 | void* result = nullptr; |
53 | 0 | if(_handle != nullptr) |
54 | 0 | { |
55 | 0 | result = dlsym(_handle, name.c_str()); |
56 | 0 | } |
57 | 0 | return result; |
58 | 0 | } |
59 | | |
60 | | const std::string& SharedLibrary::getPath() const |
61 | 0 | { |
62 | 0 | return _path; |
63 | 0 | } |
64 | | |
65 | | std::string SharedLibrary::prefix() |
66 | 0 | { |
67 | | #if BT_OS == BT_OS_CYGWIN |
68 | | return "cyg"; |
69 | | #else |
70 | 0 | return "lib"; |
71 | 0 | #endif |
72 | 0 | } |
73 | | |
74 | | std::string SharedLibrary::suffix() |
75 | 0 | { |
76 | | #if BT_OS == BT_OS_MAC_OS_X |
77 | | #if defined(_DEBUG) && !defined(CL_NO_SHARED_LIBRARY_DEBUG_SUFFIX) |
78 | | return "d.dylib"; |
79 | | #else |
80 | | return ".dylib"; |
81 | | #endif |
82 | | #elif BT_OS == BT_OS_HPUX |
83 | | #if defined(_DEBUG) && !defined(CL_NO_SHARED_LIBRARY_DEBUG_SUFFIX) |
84 | | return "d.sl"; |
85 | | #else |
86 | | return ".sl"; |
87 | | #endif |
88 | | #elif BT_OS == BT_OS_CYGWIN |
89 | | #if defined(_DEBUG) && !defined(CL_NO_SHARED_LIBRARY_DEBUG_SUFFIX) |
90 | | return "d.dll"; |
91 | | #else |
92 | | return ".dll"; |
93 | | #endif |
94 | | #else |
95 | | #if defined(_DEBUG) && !defined(CL_NO_SHARED_LIBRARY_DEBUG_SUFFIX) |
96 | | return "d.so"; |
97 | | #else |
98 | 0 | return ".so"; |
99 | 0 | #endif |
100 | 0 | #endif |
101 | 0 | } |
102 | | |
103 | | } // namespace BT |