openrave.org

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
orpythonbinding.cpp
Go to the documentation of this file.
1 
30 #include <openrave/openrave.h>
31 
32 #include <boost/python.hpp>
33 #include <boost/python/exception_translator.hpp>
34 #include <boost/python/stl_iterator.hpp>
35 #include <pyconfig.h>
36 
37 #include <exception>
38 #include <boost/shared_ptr.hpp>
39 #include <boost/format.hpp>
40 #include <boost/assert.hpp>
41 
42 #include <vector>
43 #include <cstring>
44 #include <sstream>
45 
46 using namespace OpenRAVE;
47 using namespace std;
48 
49 namespace cppexamples {
50 
51 class FunctionUserData : public UserData
52 {
53 public:
54  virtual ~FunctionUserData() {
55  }
56  boost::python::object simulationfn;
57 };
58 
60 {
61 public:
62  PythonBindingModule(EnvironmentBasePtr penv, std::istream&) : ModuleBase(penv) {
63  SetUserData(UserDataPtr(new FunctionUserData()));
64  }
66  RAVELOG_DEBUG("destroying python binding\n");
67  }
68 
69  virtual bool SimulationStep(dReal fElapsedTime) {
70  boost::shared_ptr<FunctionUserData> p = boost::dynamic_pointer_cast<FunctionUserData>(GetUserData());
71  bool ret = false;
72  if( !!p ) {
73  PyGILState_STATE gstate = PyGILState_Ensure();
74  try {
75  ret = p->simulationfn(fElapsedTime);
76  }
77  catch(...) {
78  RAVELOG_WARN("unknown exception in python callback, please register again:\n");
79  PyErr_Print();
80  ret = true;
81  }
82  PyGILState_Release(gstate);
83  if( ret ) {
84  GetEnv()->Remove(shared_from_this());
85  }
86  }
87  return ret;
88  }
89 };
90 
91 boost::shared_ptr<void> g_PythonBindingInterfaceHandle;
92 
94 {
95  return InterfaceBasePtr(new PythonBindingModule(penv,istream));
96 }
97 
98 InterfaceBasePtr RegisterSimulationFunction(int environmentid, boost::python::object simulationfn)
99 {
100  ModuleBasePtr module = RaveCreateModule(RaveGetEnvironment(environmentid), "PythonBinding");
101  if( !!module ) {
102  boost::shared_ptr<FunctionUserData> p = boost::dynamic_pointer_cast<FunctionUserData>(module->GetUserData());
103  p->simulationfn = simulationfn;
104  module->GetEnv()->Add(module,true,"");
105  }
106  return InterfaceBasePtr(module);
107 }
108 
109 void Init(UserDataPtr globalstate)
110 {
111  RaveInitializeFromState(globalstate);
114  }
115 }
116 
117 } // end namespace cppexamples
118 
119 BOOST_PYTHON_MODULE(orpythonbinding)
120 {
121  boost::python::def("Init", cppexamples::Init, boost::python::args("globalstate"), "initializes the python bindings with the openrave global state");
122  boost::python::def("RegisterSimulationFunction", cppexamples::RegisterSimulationFunction, boost::python::args("environmentid","simulationfn"));
123 };