mystring.cpp
Go to the documentation of this file.
1 /* Tutorial with boost::python. Using the converter to access a home-made
2  * string class and bind it to the python strings. */
3 
4 #include <boost/python/module.hpp>
5 #include <boost/python/def.hpp>
6 #include <boost/python/to_python_converter.hpp>
7 
8 namespace homemadestring
9 {
10 
11  /* This is the home-made string class. */
13  {
14  public:
16  custom_string(std::string const& value) : value_(value) {}
17  std::string const& value() const { return value_; }
18  private:
19  std::string value_;
20  };
21 
22  /* Two simple functions with this class */
23  custom_string hello() { return custom_string("Hello world."); }
24  std::size_t size(custom_string const& s) { return s.value().size(); }
25 
26 
27  /* From c to python converter */
29  {
30  static PyObject* convert(custom_string const& s)
31  {
32  return boost::python::incref(boost::python::object(s.value()).ptr());
33  }
34  };
35 
37  {
39  {
40  boost::python::converter::registry
41  ::push_back(&convertible,
42  &construct,
43  boost::python::type_id<custom_string>());
44  }
45 
46  static void* convertible(PyObject* obj_ptr)
47  {
48  if (!PyString_Check(obj_ptr)) return 0;
49  return obj_ptr;
50  }
51 
52  static void
53  construct(PyObject* obj_ptr,
54  boost::python::converter::rvalue_from_python_stage1_data* data)
55  {
56  const char* value = PyString_AsString(obj_ptr);
57  if (value == 0) boost::python::throw_error_already_set();
58  void* storage =
59  ((boost::python::converter::rvalue_from_python_storage<custom_string>*)data)
60  ->storage.bytes;
61  new (storage) custom_string(value);
62  data->convertible = storage;
63  }
64  };
65 
66  void init_module()
67  {
68  using namespace boost::python;
69 
70  boost::python::to_python_converter<custom_string,
73 
74  def("hello", hello);
75  def("size", size);
76  }
77 
78 } // namespace homemagestring
79 
80 BOOST_PYTHON_MODULE(libmystring)
81 {
83 }
std::size_t size(custom_string const &s)
Definition: mystring.cpp:24
void init_module()
Definition: mystring.cpp:66
BOOST_PYTHON_MODULE(libmystring)
Definition: mystring.cpp:80
data
Definition: setup.in.py:38
std::string const & value() const
Definition: mystring.cpp:17
static void * convertible(PyObject *obj_ptr)
Definition: mystring.cpp:46
static void construct(PyObject *obj_ptr, boost::python::converter::rvalue_from_python_stage1_data *data)
Definition: mystring.cpp:53
custom_string(std::string const &value)
Definition: mystring.cpp:16
static PyObject * convert(custom_string const &s)
Definition: mystring.cpp:30
custom_string hello()
Definition: mystring.cpp:23


eigenpy
Author(s): Justin Carpentier, Nicolas Mansard
autogenerated on Sat Apr 17 2021 02:37:59