a_map_indexing_suite.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. #include <boost/python/suite/indexing/map_indexing_suite.hpp>
  5. #include <boost/python/module.hpp>
  6. #include <boost/python/def.hpp>
  7. #include <boost/python/implicit.hpp>
  8. using namespace boost::python;
  9. struct A
  10. {
  11. int value;
  12. A() : value(0){};
  13. A(int v) : value(v) {};
  14. };
  15. bool operator==(const A& v1, const A& v2)
  16. {
  17. return (v1.value == v2.value);
  18. }
  19. struct B
  20. {
  21. A a;
  22. };
  23. // Converter from A to python int
  24. struct AToPython
  25. {
  26. static PyObject* convert(const A& s)
  27. {
  28. return boost::python::incref(boost::python::object((int)s.value).ptr());
  29. }
  30. };
  31. // Conversion from python int to A
  32. struct AFromPython
  33. {
  34. AFromPython()
  35. {
  36. boost::python::converter::registry::push_back(
  37. &convertible,
  38. &construct,
  39. boost::python::type_id< A >());
  40. }
  41. static void* convertible(PyObject* obj_ptr)
  42. {
  43. #if PY_VERSION_HEX >= 0x03000000
  44. if (!PyLong_Check(obj_ptr)) return 0;
  45. #else
  46. if (!PyInt_Check(obj_ptr)) return 0;
  47. #endif
  48. return obj_ptr;
  49. }
  50. static void construct(
  51. PyObject* obj_ptr,
  52. boost::python::converter::rvalue_from_python_stage1_data* data)
  53. {
  54. void* storage = (
  55. (boost::python::converter::rvalue_from_python_storage< A >*)
  56. data)-> storage.bytes;
  57. #if PY_VERSION_HEX >= 0x03000000
  58. new (storage) A((int)PyLong_AsLong(obj_ptr));
  59. #else
  60. new (storage) A((int)PyInt_AsLong(obj_ptr));
  61. #endif
  62. data->convertible = storage;
  63. }
  64. };
  65. void a_map_indexing_suite()
  66. {
  67. to_python_converter< A , AToPython >();
  68. AFromPython();
  69. class_< std::map<int, A> >("AMap")
  70. .def(map_indexing_suite<std::map<int, A>, true >())
  71. ;
  72. class_< B >("B")
  73. .add_property("a", make_getter(&B::a, return_value_policy<return_by_value>()),
  74. make_setter(&B::a, return_value_policy<return_by_value>()))
  75. ;
  76. }