signal-wrapper.hh
Go to the documentation of this file.
1 // Copyright (c) 2018, Joseph Mirabel
2 // Authors: Joseph Mirabel (joseph.mirabel@laas.fr)
3 
4 #ifndef DGPY_SIGNAL_WRAPPER
5 #define DGPY_SIGNAL_WRAPPER
6 
7 #include <dynamic-graph/linear-algebra.h>
8 #include <dynamic-graph/signal.h>
9 #include <dynamic-graph/entity.h>
11 
12 namespace dynamicgraph {
13 namespace python {
14 namespace signalWrapper {
15 void convert(PyObject* o, int& v);
16 void convert(PyObject* o, bool& v);
17 void convert(PyObject* o, float& v);
18 void convert(PyObject* o, double& v);
19 // void convert (PyObject* o, std::string& v);
20 void convert(PyObject* o, Vector& v);
21 // void convert (PyObject* o, Eigen::MatrixXd& v);
22 // void convert (PyObject* o, Eigen::Matrix4d& v);
23 } // namespace signalWrapper
24 
25 class PythonSignalContainer : public Entity {
26  DYNAMIC_GRAPH_ENTITY_DECL();
27 
28  public:
29  PythonSignalContainer(const std::string& name);
30 
31  void signalRegistration(const SignalArray<int>& signals);
32 
33  void rmSignal(const std::string& name);
34 };
35 
36 template <class T, class Time>
37 class SignalWrapper : public Signal<T, Time> {
38  public:
39  typedef Signal<T, Time> parent_t;
40 
41  static bool checkCallable(PyObject* c, std::string& error);
42 
43  SignalWrapper(std::string name, PyObject* _callable) : parent_t(name), callable(_callable) {
44  typedef boost::function2<T&, T&, Time> function_t;
45  Py_INCREF(callable);
46  function_t f = boost::bind(&SignalWrapper::call, this, _1, _2);
47  this->setFunction(f);
48  }
49 
50  virtual ~SignalWrapper() { Py_DECREF(callable); };
51 
52  private:
53  T& call(T& value, Time t) {
54  PyGILState_STATE gstate;
55  gstate = PyGILState_Ensure();
56  if (PyGILState_GetThisThreadState() == NULL) {
57  dgDEBUG(10) << "python thread not initialized" << std::endl;
58  }
59  char format[] = "i";
60  PyObject* obj = PyObject_CallFunction(callable, format, t);
61  if (obj == NULL) {
62  dgERROR << "Could not call callable" << std::endl;
63  } else {
64  signalWrapper::convert(obj, value);
65  Py_DECREF(obj);
66  }
67  PyGILState_Release(gstate);
68  return value;
69  }
70  PyObject* callable;
71 };
72 
73 } // namespace python
74 } // namespace dynamicgraph
75 #endif
Definition: signal-wrapper.hh:25
Definition: signal-wrapper.hh:37
SignalWrapper(std::string name, PyObject *_callable)
Definition: signal-wrapper.hh:43
Signal< T, Time > parent_t
Definition: signal-wrapper.hh:39
virtual ~SignalWrapper()
Definition: signal-wrapper.hh:50
Definition: convert-dg-to-py.hh:7
void convert(PyObject *o, int &v)
Definition: signal-wrapper.cc:13