Go to the documentation of this file.00001 #include <string>
00002 #include <mutex>
00003 #include <dlfcn.h>
00004 #include "behaviortree_cpp/utils/shared_library.h"
00005 #include "behaviortree_cpp/exceptions.h"
00006
00007 namespace BT
00008 {
00009 SharedLibrary::SharedLibrary()
00010 {
00011 _handle = nullptr;
00012 }
00013
00014 void SharedLibrary::load(const std::string& path, int)
00015 {
00016 std::unique_lock<std::mutex> lock(_mutex);
00017
00018 if (_handle)
00019 {
00020 throw RuntimeError("Library already loaded: " + path);
00021 }
00022
00023 _handle = dlopen(path.c_str(), RTLD_NOW | RTLD_GLOBAL);
00024 if (!_handle)
00025 {
00026 const char* err = dlerror();
00027 throw RuntimeError("Could not load library: " + (err ? std::string(err) : path));
00028 }
00029 _path = path;
00030 }
00031
00032 void SharedLibrary::unload()
00033 {
00034 std::unique_lock<std::mutex> lock(_mutex);
00035
00036 if (_handle)
00037 {
00038 dlclose(_handle);
00039 _handle = nullptr;
00040 }
00041 }
00042
00043 bool SharedLibrary::isLoaded() const
00044 {
00045 return _handle != nullptr;
00046 }
00047
00048 void* SharedLibrary::findSymbol(const std::string& name)
00049 {
00050 std::unique_lock<std::mutex> lock(_mutex);
00051
00052 void* result = nullptr;
00053 if (_handle)
00054 {
00055 result = dlsym(_handle, name.c_str());
00056 }
00057 return result;
00058 }
00059
00060 const std::string& SharedLibrary::getPath() const
00061 {
00062 return _path;
00063 }
00064
00065 std::string SharedLibrary::prefix()
00066 {
00067 #if BT_OS == BT_OS_CYGWIN
00068 return "cyg";
00069 #else
00070 return "lib";
00071 #endif
00072 }
00073
00074 std::string SharedLibrary::suffix()
00075 {
00076 #if BT_OS == BT_OS_MAC_OS_X
00077 #if defined(_DEBUG) && !defined(CL_NO_SHARED_LIBRARY_DEBUG_SUFFIX)
00078 return "d.dylib";
00079 #else
00080 return ".dylib";
00081 #endif
00082 #elif BT_OS == BT_OS_HPUX
00083 #if defined(_DEBUG) && !defined(CL_NO_SHARED_LIBRARY_DEBUG_SUFFIX)
00084 return "d.sl";
00085 #else
00086 return ".sl";
00087 #endif
00088 #elif BT_OS == BT_OS_CYGWIN
00089 #if defined(_DEBUG) && !defined(CL_NO_SHARED_LIBRARY_DEBUG_SUFFIX)
00090 return "d.dll";
00091 #else
00092 return ".dll";
00093 #endif
00094 #else
00095 #if defined(_DEBUG) && !defined(CL_NO_SHARED_LIBRARY_DEBUG_SUFFIX)
00096 return "d.so";
00097 #else
00098 return ".so";
00099 #endif
00100 #endif
00101 }
00102
00103 }