andreas_beyer.cpp 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright David Abrahams 2006. 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.hpp>
  5. #include <boost/enable_shared_from_this.hpp>
  6. #include <boost/shared_ptr.hpp>
  7. using namespace boost;
  8. class A : public enable_shared_from_this<A> {
  9. public:
  10. A() : val(0) {};
  11. int val;
  12. typedef shared_ptr<A> A_ptr;
  13. A_ptr self() {
  14. A_ptr self;
  15. self = shared_from_this();
  16. return self;
  17. }
  18. };
  19. class B {
  20. public:
  21. B() {
  22. a = A::A_ptr(new A());
  23. }
  24. void set(A::A_ptr _a) {
  25. this->a = _a;
  26. }
  27. A::A_ptr get() {
  28. return a;
  29. }
  30. A::A_ptr a;
  31. };
  32. template <class T>
  33. void hold_python(shared_ptr<T>& x)
  34. {
  35. x = python::extract<shared_ptr<T> >( python::object(x) );
  36. }
  37. A::A_ptr get_b_a(shared_ptr<B> b)
  38. {
  39. hold_python(b->a);
  40. return b->get();
  41. }
  42. BOOST_PYTHON_MODULE(andreas_beyer_ext) {
  43. python::class_<A, noncopyable> ("A")
  44. .def("self", &A::self)
  45. .def_readwrite("val", &A::val)
  46. ;
  47. python::register_ptr_to_python< A::A_ptr >();
  48. python::class_<B>("B")
  49. .def("set", &B::set)
  50. // .def("get", &B::get)
  51. .def("get", get_b_a)
  52. ;
  53. }