1 // Copyright Joel de Guzman 2004. Distributed under the Boost
2 // Software License, Version 1.0. (See accompanying
3 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
4
5 #include <boost/python/suite/indexing/map_indexing_suite.hpp>
6 #include <boost/python/module.hpp>
7 #include <boost/python/def.hpp>
8 #include <boost/python/implicit.hpp>
9
10 using namespace boost::python;
11
12 struct A
13 {
14 int value;
AA15 A() : value(0){};
AA16 A(int v) : value(v) {};
17 };
18
operator ==(const A & v1,const A & v2)19 bool operator==(const A& v1, const A& v2)
20 {
21 return (v1.value == v2.value);
22 }
23
24 struct B
25 {
26 A a;
27 };
28
29 // Converter from A to python int
30 struct AToPython
31 {
convertAToPython32 static PyObject* convert(const A& s)
33 {
34 return boost::python::incref(boost::python::object((int)s.value).ptr());
35 }
36 };
37
38 // Conversion from python int to A
39 struct AFromPython
40 {
AFromPythonAFromPython41 AFromPython()
42 {
43 boost::python::converter::registry::push_back(
44 &convertible,
45 &construct,
46 boost::python::type_id< A >());
47 }
48
convertibleAFromPython49 static void* convertible(PyObject* obj_ptr)
50 {
51 #if PY_VERSION_HEX >= 0x03000000
52 if (!PyLong_Check(obj_ptr)) return 0;
53 #else
54 if (!PyInt_Check(obj_ptr)) return 0;
55 #endif
56 return obj_ptr;
57 }
58
constructAFromPython59 static void construct(
60 PyObject* obj_ptr,
61 boost::python::converter::rvalue_from_python_stage1_data* data)
62 {
63 void* storage = (
64 (boost::python::converter::rvalue_from_python_storage< A >*)
65 data)-> storage.bytes;
66
67 #if PY_VERSION_HEX >= 0x03000000
68 new (storage) A((int)PyLong_AsLong(obj_ptr));
69 #else
70 new (storage) A((int)PyInt_AsLong(obj_ptr));
71 #endif
72 data->convertible = storage;
73 }
74 };
75
a_map_indexing_suite()76 void a_map_indexing_suite()
77 {
78
79 to_python_converter< A , AToPython >();
80 AFromPython();
81
82 class_< std::map<int, A> >("AMap")
83 .def(map_indexing_suite<std::map<int, A>, true >())
84 ;
85
86 class_< B >("B")
87 .add_property("a", make_getter(&B::a, return_value_policy<return_by_value>()),
88 make_setter(&B::a, return_value_policy<return_by_value>()))
89 ;
90 }
91
92
93