OSSIA
Open Scenario System for Interactive Application
dylib_loader.hpp
1 #pragma once
2 
3 #if __has_include(<dlfcn.h>)
4 #include <ossia/detail/fmt.hpp>
5 
6 #include <dlfcn.h>
7 
8 #include <stdexcept>
9 
10 namespace ossia
11 {
12 class dylib_loader
13 {
14 public:
15  explicit dylib_loader(const char* const so)
16  {
17  impl = dlopen(so, RTLD_LAZY | RTLD_LOCAL | RTLD_NODELETE);
18  if(!impl)
19  {
20  throw std::runtime_error(fmt::format("{}: not found. ", so));
21  }
22  }
23 
24  explicit dylib_loader(std::vector<std::string_view> sos)
25  {
26  if(sos.empty())
27  throw std::runtime_error("No shared object specified");
28 
29  for(const auto so : sos)
30  {
31  impl = dlopen(so.data(), RTLD_LAZY | RTLD_LOCAL | RTLD_NODELETE);
32  if(impl)
33  return;
34  }
35 
36  throw std::runtime_error(fmt::format("{}: not found. ", sos[0]));
37  }
38 
39  dylib_loader(const dylib_loader&) noexcept = delete;
40  dylib_loader& operator=(const dylib_loader&) noexcept = delete;
41  dylib_loader(dylib_loader&& other) noexcept
42  {
43  impl = other.impl;
44  other.impl = nullptr;
45  }
46 
47  dylib_loader& operator=(dylib_loader&& other) noexcept
48  {
49  impl = other.impl;
50  other.impl = nullptr;
51  return *this;
52  }
53 
54  ~dylib_loader()
55  {
56  if(impl)
57  {
58  dlclose(impl);
59  }
60  }
61 
62  template <typename T>
63  T symbol(const char* const sym) const noexcept
64  {
65  return (T)dlsym(impl, sym);
66  }
67 
68  operator bool() const { return bool(impl); }
69 
70 private:
71  void* impl{};
72 };
73 }
74 #endif
Definition: git_info.h:7