Advertisement
dan-masek

Untitled

May 24th, 2019
375
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.19 KB | None | 0 0
  1. #include <boost/python.hpp>
  2. #include <boost/python/stl_iterator.hpp>
  3. #include <boost/shared_ptr.hpp>
  4. #include <boost/make_shared.hpp>
  5. #include <list>
  6.  
  7. struct MyClass
  8. {
  9.     MyClass(std::list<std::string> messages) : msgs(messages) {}
  10.  
  11.     std::list<std::string> msgs;
  12. };
  13.  
  14. namespace bp = boost::python;
  15.  
  16. boost::shared_ptr<MyClass> create_MyClass(bp::list const& l)
  17. {
  18.     std::list<std::string> messages;
  19.     messages.assign(bp::stl_input_iterator<std::string>(l)
  20.         , bp::stl_input_iterator<std::string>());
  21.  
  22.     return boost::make_shared<MyClass>(messages);
  23. }
  24.  
  25.  
  26. struct std_list_to_python
  27. {
  28.     static PyObject* convert(std::list<std::string> const& l)
  29.     {
  30.         bp::list result;
  31.         for (auto const& value : l) {
  32.             result.append(value);
  33.         }
  34.         return bp::incref(result.ptr());
  35.     }
  36. };
  37.  
  38.  
  39. struct pylist_converter
  40. {
  41.     static void* convertible(PyObject* object)
  42.     {
  43.         return PyList_Check(object) ? object : NULL;
  44.     }
  45.  
  46.     static void construct(PyObject* object, bp::converter::rvalue_from_python_stage1_data* data)
  47.     {
  48.         bp::handle<> handle(bp::borrowed(object));
  49.  
  50.         typedef bp::converter::rvalue_from_python_storage<std::list<std::string>> storage_type;
  51.         void* storage = reinterpret_cast<storage_type*>(data)->storage.bytes;
  52.  
  53.         data->convertible = new (storage) std::list<std::string>();
  54.  
  55.         std::list<std::string>* l = (std::list<std::string>*)(storage);
  56.  
  57.         int sz = PySequence_Size(object);
  58.         for (int i = 0; i < sz; ++i) {
  59.             l->push_back(bp::extract<std::string>(PyList_GetItem(object, i)));
  60.         }
  61.     }
  62. };
  63.  
  64.  
  65.  
  66. BOOST_PYTHON_MODULE(so07)
  67. {
  68. //     bp::class_<MyClass, boost::noncopyable, boost::shared_ptr<MyClass>>("MyClass", bp::no_init)
  69. //         .def("__init__", bp::make_constructor(create_MyClass))
  70. //         ;
  71.  
  72.  
  73.     bp::to_python_converter<std::list<std::string>, std_list_to_python>();
  74.  
  75.     bp::converter::registry::push_back(&pylist_converter::convertible
  76.         , &pylist_converter::construct
  77.         , bp::type_id<std::list<std::string>>());
  78.  
  79.     bp::class_<MyClass, boost::noncopyable>("MyClass", bp::init<std::list<std::string>>())
  80.         ;
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement