test_pointer_adoption.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. // Copyright David Abrahams 2002.
  2. // Distributed under the Boost Software License, Version 1.0. (See
  3. // accompanying file LICENSE_1_0.txt or copy at
  4. // http://www.boost.org/LICENSE_1_0.txt)
  5. #include <boost/python/module.hpp>
  6. #include <boost/python/def.hpp>
  7. #include <boost/python/return_value_policy.hpp>
  8. #include <boost/python/manage_new_object.hpp>
  9. #include <boost/python/return_internal_reference.hpp>
  10. #include <boost/python/class.hpp>
  11. using namespace boost::python;
  12. int a_instances = 0;
  13. int num_a_instances() { return a_instances; }
  14. struct inner
  15. {
  16. inner(std::string const& s)
  17. : s(s)
  18. {}
  19. void change(std::string const& new_s)
  20. {
  21. this->s = new_s;
  22. }
  23. std::string s;
  24. };
  25. struct Base
  26. {
  27. virtual ~Base() {}
  28. };
  29. struct A : Base
  30. {
  31. A(std::string const& s)
  32. : x(s)
  33. {
  34. ++a_instances;
  35. }
  36. ~A()
  37. {
  38. --a_instances;
  39. }
  40. std::string content() const
  41. {
  42. return x.s;
  43. }
  44. inner& get_inner()
  45. {
  46. return x;
  47. }
  48. inner x;
  49. };
  50. struct B
  51. {
  52. B() : x(0) {}
  53. B(A* x_) : x(x_) {}
  54. inner const* adopt(A* _x) { this->x = _x; return &_x->get_inner(); }
  55. std::string a_content()
  56. {
  57. return x ? x->content() : std::string("empty");
  58. }
  59. A* x;
  60. };
  61. A* create(std::string const& s)
  62. {
  63. return new A(s);
  64. }
  65. A* as_A(Base* b)
  66. {
  67. return dynamic_cast<A*>(b);
  68. }
  69. BOOST_PYTHON_MODULE(test_pointer_adoption_ext)
  70. {
  71. def("num_a_instances", num_a_instances);
  72. // Specify the manage_new_object return policy to take
  73. // ownership of create's result
  74. def("create", create, return_value_policy<manage_new_object>());
  75. def("as_A", as_A, return_internal_reference<>());
  76. class_<Base>("Base")
  77. ;
  78. class_<A, bases<Base> >("A", no_init)
  79. .def("content", &A::content)
  80. .def("get_inner", &A::get_inner, return_internal_reference<>())
  81. ;
  82. class_<inner>("inner", no_init)
  83. .def("change", &inner::change)
  84. ;
  85. class_<B>("B")
  86. .def(init<A*>()[with_custodian_and_ward_postcall<1,2>()])
  87. .def("adopt", &B::adopt
  88. // Adopt returns a pointer referring to a subobject of its 2nd argument (1st being "self")
  89. , return_internal_reference<2
  90. // Meanwhile, self holds a reference to the 2nd argument.
  91. , with_custodian_and_ward<1,2> >()
  92. )
  93. .def("a_content", &B::a_content)
  94. ;
  95. }
  96. #include "module_tail.cpp"