diff options
author | Sergey Yershov <syershov@maps.me> | 2016-11-15 17:14:43 +0300 |
---|---|---|
committer | Sergey Yershov <syershov@maps.me> | 2016-11-16 15:04:22 +0300 |
commit | 715c6cac0c6297f350c83c1126954f8d5b188bf4 (patch) | |
tree | dc449a5e7789632a2a638d64e46b167cc6825184 /pyhelpers | |
parent | cf1f3d1fccbb11c6a1bf14450f43ffd3e4d1852f (diff) |
Add python bindings for traffic
Diffstat (limited to 'pyhelpers')
-rw-r--r-- | pyhelpers/pair.hpp | 29 | ||||
-rw-r--r-- | pyhelpers/vector_uint8.hpp | 47 |
2 files changed, 76 insertions, 0 deletions
diff --git a/pyhelpers/pair.hpp b/pyhelpers/pair.hpp new file mode 100644 index 0000000000..54155aed4c --- /dev/null +++ b/pyhelpers/pair.hpp @@ -0,0 +1,29 @@ +#pragma once + +#include "std/utility.hpp" + +#include <boost/python.hpp> +#include <boost/python/suite/indexing/vector_indexing_suite.hpp> + +namespace +{ +using namespace boost::python; + +// Converts a std::pair instance to a Python tuple. +template <typename T1, typename T2> +struct pair_to_tuple +{ + static PyObject * convert(pair<T1, T2> const & p) + { + return incref(make_tuple(p.first, p.second).ptr()); + } + + static PyTypeObject const * get_pytype() { return &PyTuple_Type; } +}; + +template <typename T1, typename T2> +struct pair_to_python_converter +{ + pair_to_python_converter() { to_python_converter<pair<T1, T2>, pair_to_tuple<T1, T2>, true>(); } +}; +} // namespace diff --git a/pyhelpers/vector_uint8.hpp b/pyhelpers/vector_uint8.hpp new file mode 100644 index 0000000000..f1bebc5ff3 --- /dev/null +++ b/pyhelpers/vector_uint8.hpp @@ -0,0 +1,47 @@ +#pragma once + +#include "std/vector.hpp" + +#include <boost/python.hpp> +#include <boost/python/suite/indexing/map_indexing_suite.hpp> + +namespace +{ +using namespace boost::python; + +// Converts a vector<uint8_t> to/from Python str. +struct vector_uint8t_to_str +{ + static PyObject * convert(vector<uint8_t> const & v) + { + str s(reinterpret_cast<char const *>(v.data()), v.size()); + return incref(s.ptr()); + } +}; + +struct vector_uint8t_from_python_str +{ + vector_uint8t_from_python_str() + { + converter::registry::push_back(&convertible, &construct, type_id<vector<uint8_t>>()); + } + + static void * convertible(PyObject * obj_ptr) + { + if (!PyString_Check(obj_ptr)) + return nullptr; + return obj_ptr; + } + + static void construct(PyObject * obj_ptr, converter::rvalue_from_python_stage1_data * data) + { + const char * value = PyString_AsString(obj_ptr); + if (value == nullptr) + throw_error_already_set(); + void * storage = + ((converter::rvalue_from_python_storage<vector<uint8_t>> *)data)->storage.bytes; + new (storage) vector<uint8_t>(value, value + PyString_Size(obj_ptr)); + data->convertible = storage; + } +}; +} // namespace |