Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <boost/python.hpp>
- #include <boost/python/stl_iterator.hpp>
- #include <boost/shared_ptr.hpp>
- #include <boost/make_shared.hpp>
- #include <list>
- struct MyClass
- {
- MyClass(std::list<std::string> messages) : msgs(messages) {}
- std::list<std::string> msgs;
- };
- namespace bp = boost::python;
- boost::shared_ptr<MyClass> create_MyClass(bp::list const& l)
- {
- std::list<std::string> messages;
- messages.assign(bp::stl_input_iterator<std::string>(l)
- , bp::stl_input_iterator<std::string>());
- return boost::make_shared<MyClass>(messages);
- }
- struct std_list_to_python
- {
- static PyObject* convert(std::list<std::string> const& l)
- {
- bp::list result;
- for (auto const& value : l) {
- result.append(value);
- }
- return bp::incref(result.ptr());
- }
- };
- struct pylist_converter
- {
- static void* convertible(PyObject* object)
- {
- return PyList_Check(object) ? object : NULL;
- }
- static void construct(PyObject* object, bp::converter::rvalue_from_python_stage1_data* data)
- {
- bp::handle<> handle(bp::borrowed(object));
- typedef bp::converter::rvalue_from_python_storage<std::list<std::string>> storage_type;
- void* storage = reinterpret_cast<storage_type*>(data)->storage.bytes;
- data->convertible = new (storage) std::list<std::string>();
- std::list<std::string>* l = (std::list<std::string>*)(storage);
- int sz = PySequence_Size(object);
- for (int i = 0; i < sz; ++i) {
- l->push_back(bp::extract<std::string>(PyList_GetItem(object, i)));
- }
- }
- };
- BOOST_PYTHON_MODULE(so07)
- {
- // bp::class_<MyClass, boost::noncopyable, boost::shared_ptr<MyClass>>("MyClass", bp::no_init)
- // .def("__init__", bp::make_constructor(create_MyClass))
- // ;
- bp::to_python_converter<std::list<std::string>, std_list_to_python>();
- bp::converter::registry::push_back(&pylist_converter::convertible
- , &pylist_converter::construct
- , bp::type_id<std::list<std::string>>());
- bp::class_<MyClass, boost::noncopyable>("MyClass", bp::init<std::list<std::string>>())
- ;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement