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 
14 namespace knowrob {
18  template<class T>
19  class PluginLibrary : public PluginFactory<T> {
20  public:
24  explicit PluginLibrary(std::string_view dllPath)
25  : dllPath_(dllPath),
26  handle_(nullptr),
27  create_(nullptr),
28  get_name_(nullptr) {
29  }
30 
31  ~PluginLibrary() override {
32  if (handle_) {
33  dlclose(handle_);
34  handle_ = nullptr;
35  }
36  }
37 
41  PluginLibrary(const PluginLibrary &) = delete;
42 
46  bool isLoaded() {
47  return (create_ != nullptr && get_name_ != nullptr);
48  }
49 
56  bool loadDLL() {
57  handle_ = dlopen(dllPath_.c_str(), RTLD_LAZY);
58  if (handle_ != nullptr) {
59  create_ = (std::shared_ptr<T> (*)()) dlsym(handle_, "knowrob_createPlugin");
60  get_name_ = (char *(*)()) dlsym(handle_, "knowrob_getPluginName");
61  return isLoaded();
62  } else {
63  return false;
64  }
65  }
66 
67  // Override PluginFactory
68  std::shared_ptr<NamedPlugin<T>> create(std::string_view pluginID) override {
69  return std::make_shared<NamedPlugin<T>>(pluginID, PluginLanguage::CPP, create_());
70  }
71 
72  // Override PluginFactory
73  std::string_view name() const override { return name_; };
74 
75  protected:
76  const std::string dllPath_;
78  // handle of opened library
79  void *handle_;
80 
81  // a factory function used to create new instances of a backend.
82  std::shared_ptr<T> (*create_)();
83 
84  // a function that returns the name of the plugin
85  char *(*get_name_)();
86  };
87 }
88 
89 #endif //KNOWROB_PLUGIN_LIBRARY_H_
std::shared_ptr< NamedPlugin< T > > create(std::string_view pluginID) override
Definition: PluginLibrary.h:68
const std::string dllPath_
Definition: PluginLibrary.h:73
std::string_view name() const override
Definition: PluginLibrary.h:73
PluginLibrary(const PluginLibrary &)=delete
PluginLibrary(std::string_view dllPath)
Definition: PluginLibrary.h:24
std::shared_ptr< T >(* create_)()
Definition: PluginLibrary.h:82
TermRule & string()
Definition: terms.cpp:63