From 3769b2058019ce7c6be824085e1047e1beec07dc Mon Sep 17 00:00:00 2001 From: David Shah Date: Thu, 7 Jun 2018 09:47:00 +0200 Subject: Adding Python to/from string wrappers for internal IDs --- common/pybindings.h | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) (limited to 'common/pybindings.h') diff --git a/common/pybindings.h b/common/pybindings.h index 84280908..5b2adc6a 100644 --- a/common/pybindings.h +++ b/common/pybindings.h @@ -76,6 +76,54 @@ struct range_wrapper { } }; +/* +A wrapper to enable custom type/ID to/from string conversions + */ +template struct string_wrapper { + template + struct from_pystring_converter { + from_pystring_converter() { + converter::registry::push_back( + &convertible, + &construct, + boost::python::type_id()); + }; + + static void* convertible(PyObject* object) { + return PyUnicode_Check(object) ? object : 0; + } + + static void construct( + PyObject* object, + converter::rvalue_from_python_stage1_data* data) { + const wchar_t* value = PyUnicode_AsUnicode(object); + const std::wstring value_ws(value); + if (value == 0) throw_error_already_set(); + void* storage = ( + (boost::python::converter::rvalue_from_python_storage*) + data)->storage.bytes; + new (storage) T(fn(std::string(value_ws.begin(), value_ws.end()))); + data->convertible = storage; + } + + static F fn; + }; + + template struct to_str_wrapper { + static F fn; + std::string str(T& x) { + return fn(x); + } + }; + + template static void wrap(const char *type_name, F1 to_str_fn, F2 from_str_fn) { + from_pystring_converter::fn = from_str_fn; + from_pystring_converter(); + to_str_wrapper::fn = to_str_fn; + class_(type_name, no_init).def("__str__", to_str_wrapper::str); + }; +}; + #define WRAP_RANGE(t) range_wrapper().wrap(#t "Range", #t "Iterator") void init_python(const char *executable); -- cgit v1.2.3