knowrob  2.1.0
A Knowledge Base System for Cognition-enabled Robots
PluginLibrary.h
Go to the documentation of this file.
1 /*
2  * This file is part of KnowRob, please consult
3  * https://github.com/knowrob/knowrob for license details.
4  */
5 
6 #ifndef KNOWROB_PLUGIN_LIBRARY_H_
7 #define KNOWROB_PLUGIN_LIBRARY_H_
8 
9 #include <string>
10 #include <memory>
11 #include <dlfcn.h>
12 #include "knowrob/plugins/PluginFactory.h"
13 #include "knowrob/Logger.h"
14 
15 namespace knowrob {
19  template<class T>
20  class PluginLibrary : public PluginFactory<T> {
21  public:
25  explicit PluginLibrary(std::string_view dllPath)
26  : dllPath_(dllPath),
27  handle_(nullptr),
28  create_(nullptr),
29  get_name_(nullptr) {
30  }
31 
32  ~PluginLibrary() override {
33  if (handle_) {
34  dlclose(handle_);
35  handle_ = nullptr;
36  }
37  }
38 
42  PluginLibrary(const PluginLibrary &) = delete;
43 
47  bool isLoaded() {
48  return (create_ != nullptr && get_name_ != nullptr);
49  }
50 
57  bool loadDLL() {
58  handle_ = dlopen(dllPath_.c_str(), RTLD_LAZY);
59  // Throw the error if the library could not be loaded
60  if (!handle_) {
61  KB_ERROR("dlopen failed: {}", dlerror());
62  };
63  if (handle_ != nullptr) {
64  create_ = (std::shared_ptr<T> (*)()) dlsym(handle_, "knowrob_createPlugin");
65  get_name_ = (char *(*)()) dlsym(handle_, "knowrob_getPluginName");
66  return isLoaded();
67  } else {
68  return false;
69  }
70  }
71 
72  // Override PluginFactory
73  std::shared_ptr<NamedPlugin<T>> create(std::string_view pluginID) override {
74  return std::make_shared<NamedPlugin<T>>(pluginID, PluginLanguage::CPP, create_());
75  }
76 
77  // Override PluginFactory
78  std::string_view name() const override { return name_; };
79 
80  protected:
81  const std::string dllPath_;
83  // handle of opened library
84  void *handle_;
85 
86  // a factory function used to create new instances of a backend.
87  std::shared_ptr<T> (*create_)();
88 
89  // a function that returns the name of the plugin
90  char *(*get_name_)();
91  };
92 }
93 
94 #endif //KNOWROB_PLUGIN_LIBRARY_H_
#define KB_ERROR
Definition: Logger.h:28
std::shared_ptr< NamedPlugin< T > > create(std::string_view pluginID) override
Definition: PluginLibrary.h:73
const std::string dllPath_
Definition: PluginLibrary.h:78
std::string_view name() const override
Definition: PluginLibrary.h:78
PluginLibrary(const PluginLibrary &)=delete
PluginLibrary(std::string_view dllPath)
Definition: PluginLibrary.h:25
std::shared_ptr< T >(* create_)()
Definition: PluginLibrary.h:87
TermRule & string()
Definition: terms.cpp:63