From c9300e07c2b209bfd2d825f5f487a276db014388 Mon Sep 17 00:00:00 2001 From: Joel de Guzman Date: Tue, 20 Jun 2006 00:33:22 +0000 Subject: [PATCH] added custom converter test for map indexing suite [SVN r34359] --- test/map_indexing_suite.cpp | 68 +++++++++++++++++++++++++++++++++++++ test/map_indexing_suite.py | 13 +++++++ 2 files changed, 81 insertions(+) diff --git a/test/map_indexing_suite.cpp b/test/map_indexing_suite.cpp index 1a548d31..8b5e3b6e 100644 --- a/test/map_indexing_suite.cpp +++ b/test/map_indexing_suite.cpp @@ -26,6 +26,62 @@ std::string x_value(X const& x) return "gotya " + x.s; } +struct A +{ + int value; + A() : value(0){}; + A(int v) : value(v) {}; +}; + +bool operator==(const A& v1, const A& v2) +{ + return (v1.value == v2.value); +} + +struct B +{ + A a; +}; + +// Converter from A to python int +struct AToPython +{ + static PyObject* convert(const A& s) + { + return boost::python::incref(boost::python::object((int)s.value).ptr()); + } +}; + +// Conversion from python int to A +struct AFromPython +{ + AFromPython() + { + boost::python::converter::registry::push_back( + &convertible, + &construct, + boost::python::type_id< A >()); + } + + static void* convertible(PyObject* obj_ptr) + { + if (!PyInt_Check(obj_ptr)) return 0; + return obj_ptr; + } + + static void construct( + PyObject* obj_ptr, + boost::python::converter::rvalue_from_python_stage1_data* data) + { + void* storage = ( + (boost::python::converter::rvalue_from_python_storage< A >*) + data)-> storage.bytes; + + new (storage) A((int)PyInt_AsLong(obj_ptr)); + data->convertible = storage; + } +}; + BOOST_PYTHON_MODULE(map_indexing_suite_ext) { class_("X") @@ -58,6 +114,18 @@ BOOST_PYTHON_MODULE(map_indexing_suite_ext) class_ > >("TestMap") .def(map_indexing_suite >, true>()) ; + + to_python_converter< A , AToPython >(); + AFromPython(); + + class_< std::map >("AMap") + .def(map_indexing_suite, true >()) + ; + + class_< B >("B") + .add_property("a", make_getter(&B::a, return_value_policy()), + make_setter(&B::a, return_value_policy())) + ; } #include "module_tail.cpp" diff --git a/test/map_indexing_suite.py b/test/map_indexing_suite.py index 646f6194..01fa943d 100644 --- a/test/map_indexing_suite.py +++ b/test/map_indexing_suite.py @@ -11,6 +11,7 @@ >>> assert "map_indexing_suite_IntMap_entry" in dir() >>> assert "map_indexing_suite_TestMap_entry" in dir() >>> assert "map_indexing_suite_XMap_entry" in dir() +>>> assert "map_indexing_suite_AMap_entry" in dir() >>> x = X('hi') >>> x hi @@ -201,6 +202,18 @@ kiwi ... dom = el.data() joel kimpo +##################################################################### +# Test custom converter... +##################################################################### + +>>> am = AMap() +>>> am[3] = 4 +>>> am[3] +4 +>>> for i in am: +... i.data() +4 + ##################################################################### # END.... #####################################################################