siplasplas
A library for C++ reflection and introspection
dynamiclibrary.hpp
1 #ifndef SIPLASPLAS_UTILITY_DYNAMICLIBRARY_HPP
2 #define SIPLASPLAS_UTILITY_DYNAMICLIBRARY_HPP
3 
4 #include <string>
5 #include <unordered_map>
6 #include <siplasplas/utility/export.hpp>
7 #include <memory>
8 
9 namespace cpp
10 {
11 
27 class SIPLASPLAS_UTILITY_EXPORT DynamicLibrary
28 {
29 public:
48  static DynamicLibrary load(const std::string& libraryPath);
49 
71  class SIPLASPLAS_UTILITY_EXPORT Symbol
72  {
73  friend class DynamicLibrary;
74  public:
75  Symbol() = default;
76 
82  const std::string& name() const;
83 
89  void* handle();
90 
96  const void* handle() const;
97 
105  template<typename T>
106  T get()
107  {
108  return reinterpret_cast<T>(handle());
109  }
110 
130  template<typename T>
132  {
133  return *get<T*>();
134  }
135 
155  template<typename T>
156  const T& getObject() const
157  {
158  return *get<T*>();
159  }
160  private:
161  void* _symbolHandle;
162  std::string _symbolName;
163  DynamicLibrary* _library;
164 
165  Symbol(DynamicLibrary& library, void* symbolHandle, const std::string& symbolName);
166 
167  static Symbol load(DynamicLibrary& library, const std::string& symbolName);
168  };
169 
182  Symbol& getSymbol(const std::string& name);
183 
190  void* handle() const;
191 
197  const std::string& path() const;
198 
199 private:
200  std::shared_ptr<void> _libraryHandle;
201  std::string _libraryPath;
202 
203  std::unordered_map<std::string, Symbol> _loadedSymbols;
204 
205  DynamicLibrary(void* libraryHandle, const std::string& libraryPath);
206 };
207 
208 }
209 
210 #endif // SIPLASPLAS_UTILITY_DYNAMICLIBRARY_HPP
Represents a symbol loaded from a dynamic library.
Definition: dynamiclibrary.hpp:71
Definition: canary_allocator.hpp:7
const T & getObject() const
Returns the symbol interpreted as a const reference to an object.
Definition: dynamiclibrary.hpp:156
Provides a cross-platform interface to load symbols from shared libraries at runtime.
Definition: dynamiclibrary.hpp:27
T & getObject()
Returns the symbol interpreted as a reference to an object.
Definition: dynamiclibrary.hpp:131