knowrob  2.1.0
A Knowledge Base System for Cognition-enabled Robots
utils.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_PY_UTILS_H
7 #define KNOWROB_PY_UTILS_H
8 
9 #include <boost/python.hpp>
10 #include <filesystem>
11 #include "PythonError.h"
12 #include "gil.h"
13 #include "with.h"
14 
15 namespace knowrob::py {
16  // call a method of a python object
17  template<typename R, typename... Args> R call_method(PyObject *self, const char *method, Args... args) {
18  try {
19  return boost::python::call_method<R>(self, method, boost::python::object(args)...);
20  } catch(const boost::python::error_already_set&) {
21  throw PythonError();
22  }
23  }
24 
29  template<typename R> R call(const std::function<R()>& goal) {
30  try {
31  return goal();
32  } catch(const boost::python::error_already_set&) {
33  throw PythonError();
34  }
35  }
36 
41  template<typename R> R call_with_gil(const std::function<R()>& goal) {
42  py::gil_lock lock;
43  return call(goal);
44  }
45 
49  class PyObj_wrap {
50  public:
51  explicit PyObj_wrap(boost::python::object self)
52  : self_(std::move(self)) {}
53 
55  gil_lock _lock;
56  self_ = boost::python::object();
57  }
58 
59  void operator()() {
60  gil_lock _lock;
61  self_();
62  }
63 
64  protected:
65  boost::python::object self_;
66  };
67 
73  std::string resolveModulePath(std::string_view modulePath);
74 
80  std::string addToSysPath(const std::filesystem::path& modulePath);
81 
86  template <typename T> void createType();
87 }
88 
89 #endif //KNOWROB_PY_UTILS_H
PyObj_wrap(boost::python::object self)
Definition: utils.h:51
boost::python::object self_
Definition: utils.h:65
FunctionRule & function()
Definition: terms.cpp:140
TermRule & string()
Definition: terms.cpp:63
std::string addToSysPath(const std::filesystem::path &modulePath)
Definition: utils.cpp:25
R call_with_gil(const std::function< R()> &goal)
Definition: utils.h:41
R call(const std::function< R()> &goal)
Definition: utils.h:29
std::string resolveModulePath(std::string_view modulePath)
Definition: utils.cpp:13
R call_method(PyObject *self, const char *method, Args... args)
Definition: utils.h:17
void createType()