wbc
std_vector_conversion.h
Go to the documentation of this file.
1#pragma once
2
3#include <boost/python.hpp>
4#include <boost/python/implicit.hpp>
5#include <boost/python/module.hpp>
6
7namespace py = boost::python;
8
9namespace pygen {
10
11/*
12 * List -> std vector converters
13 */
14
15template <class StdVectorType>
18 {
19 py::converter::registry::push_back(&convertible, &construct, py::type_id<StdVectorType>());
20 }
21
22 static void* convertible(PyObject* obj_ptr)
23 {
24 if (!PySequence_Check(obj_ptr))
25 return 0;
26
27 py::list arr = py::extract<py::list>(obj_ptr);
28 return obj_ptr;
29 }
30
31 static void construct(PyObject* obj_ptr, py::converter::rvalue_from_python_stage1_data* data)
32 {
33 py::list arr = py::extract<py::list>(obj_ptr);
34 auto len = py::len(arr);
35
36 using storage_type = py::converter::rvalue_from_python_storage<StdVectorType>;
37 void* storage = reinterpret_cast<storage_type*>(data)->storage.bytes;
38
39 new (storage) StdVectorType;
40 StdVectorType& vec = *static_cast<StdVectorType*>(storage);
41
42 vec.resize(len);
43
44 for (long i = 0; i < len; ++i)
45 vec[i] = py::extract<typename StdVectorType::value_type>(arr[i]);
46
47 data->convertible = storage;
48 }
49};
50
51/*
52 * To std vector -> List convertors
53 */
54
55template <typename StdVectorType>
57 static PyObject* convert(const StdVectorType& vec)
58 {
59 boost::python::list l;
60 for (int i = 0; i < vec.size(); i++)
61 l.append(vec[i]);
62 return py::incref(l.ptr());
63 }
64};
65
66
67/*
68 * Main converters
69 */
70template <typename StdVectorType>
72{
74 py::to_python_converter<StdVectorType, std_vector_to_python_list<StdVectorType> >();
75}
76
77} // namespace pygen
Definition base_types_conversion.h:41
void convertStdVector()
Definition std_vector_conversion.h:71
Definition std_vector_conversion.h:16
static void * convertible(PyObject *obj_ptr)
Definition std_vector_conversion.h:22
python_list_to_std_vector()
Definition std_vector_conversion.h:17
static void construct(PyObject *obj_ptr, py::converter::rvalue_from_python_stage1_data *data)
Definition std_vector_conversion.h:31
Definition std_vector_conversion.h:56
static PyObject * convert(const StdVectorType &vec)
Definition std_vector_conversion.h:57