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