signal-wrapper.hh 1.51 KB
Newer Older
1
2
3
// Copyright (c) 2018, Joseph Mirabel
// Authors: Joseph Mirabel (joseph.mirabel@laas.fr)

Guilhem Saurel's avatar
Guilhem Saurel committed
4
5
6
#ifndef DGPY_SIGNAL_WRAPPER
#define DGPY_SIGNAL_WRAPPER

Joseph Mirabel's avatar
Joseph Mirabel committed
7
8
#include <boost/python.hpp>

9
10
#include <dynamic-graph/linear-algebra.h>
#include <dynamic-graph/signal.h>
11
#include <dynamic-graph/entity.h>
12
#include "dynamic-graph/python/python-compat.hh"
13
14

namespace dynamicgraph {
Guilhem Saurel's avatar
format    
Guilhem Saurel committed
15
namespace python {
16

Guilhem Saurel's avatar
format    
Guilhem Saurel committed
17
18
class PythonSignalContainer : public Entity {
  DYNAMIC_GRAPH_ENTITY_DECL();
19

Guilhem Saurel's avatar
format    
Guilhem Saurel committed
20
 public:
Joseph Mirabel's avatar
Joseph Mirabel committed
21
  using Entity::Entity;
22

Guilhem Saurel's avatar
format    
Guilhem Saurel committed
23
  void signalRegistration(const SignalArray<int>& signals);
24

Guilhem Saurel's avatar
format    
Guilhem Saurel committed
25
26
  void rmSignal(const std::string& name);
};
27

Guilhem Saurel's avatar
format    
Guilhem Saurel committed
28
29
30
31
template <class T, class Time>
class SignalWrapper : public Signal<T, Time> {
 public:
  typedef Signal<T, Time> parent_t;
Joseph Mirabel's avatar
Joseph Mirabel committed
32
  typedef boost::python::object pyobject;
33

Joseph Mirabel's avatar
Joseph Mirabel committed
34
  static bool checkCallable(pyobject c, std::string& error);
35

Joseph Mirabel's avatar
Joseph Mirabel committed
36
  SignalWrapper(std::string name, pyobject callable) : parent_t(name), callable(callable) {
Guilhem Saurel's avatar
format    
Guilhem Saurel committed
37
38
39
40
    typedef boost::function2<T&, T&, Time> function_t;
    function_t f = boost::bind(&SignalWrapper::call, this, _1, _2);
    this->setFunction(f);
  }
41

Guilhem Saurel's avatar
Format    
Guilhem Saurel committed
42
  virtual ~SignalWrapper(){};
43

Guilhem Saurel's avatar
format    
Guilhem Saurel committed
44
45
46
47
48
49
50
 private:
  T& call(T& value, Time t) {
    PyGILState_STATE gstate;
    gstate = PyGILState_Ensure();
    if (PyGILState_GetThisThreadState() == NULL) {
      dgDEBUG(10) << "python thread not initialized" << std::endl;
    }
Joseph Mirabel's avatar
Joseph Mirabel committed
51
52
    pyobject obj = callable(t);
    value = boost::python::extract<T>(obj);
Guilhem Saurel's avatar
format    
Guilhem Saurel committed
53
54
55
    PyGILState_Release(gstate);
    return value;
  }
Joseph Mirabel's avatar
Joseph Mirabel committed
56
  pyobject callable;
Guilhem Saurel's avatar
format    
Guilhem Saurel committed
57
};
58

Guilhem Saurel's avatar
format    
Guilhem Saurel committed
59
60
}  // namespace python
}  // namespace dynamicgraph
Guilhem Saurel's avatar
Guilhem Saurel committed
61
#endif