| 1 | #include <boost/python/module.hpp>
|
|---|
| 2 | #include <boost/python/class.hpp>
|
|---|
| 3 | #include <boost/python/return_internal_reference.hpp>
|
|---|
| 4 |
|
|---|
| 5 | class Bar
|
|---|
| 6 | {
|
|---|
| 7 | public:
|
|---|
| 8 | Bar(int x) : x(x) {}
|
|---|
| 9 | int get_x() const { return x; }
|
|---|
| 10 | void set_x(int x) { this->x = x; }
|
|---|
| 11 | private:
|
|---|
| 12 | int x;
|
|---|
| 13 | };
|
|---|
| 14 |
|
|---|
| 15 | class Foo
|
|---|
| 16 | {
|
|---|
| 17 | public:
|
|---|
| 18 | Foo(int x) : b(x) {}
|
|---|
| 19 |
|
|---|
| 20 | // Returns an internal reference
|
|---|
| 21 | Bar const& get_bar() const { return b; }
|
|---|
| 22 |
|
|---|
| 23 | private:
|
|---|
| 24 | Bar b;
|
|---|
| 25 | };
|
|---|
| 26 |
|
|---|
| 27 | using namespace boost::python;
|
|---|
| 28 | BOOST_PYTHON_MODULE(internal_refs)
|
|---|
| 29 | {
|
|---|
| 30 | class_<Bar>("Bar", init<int>())
|
|---|
| 31 | .def("get_x", &Bar::get_x)
|
|---|
| 32 | .def("set_x", &Bar::set_x)
|
|---|
| 33 | ;
|
|---|
| 34 |
|
|---|
| 35 | class_<Foo>("Foo", init<int>())
|
|---|
| 36 | .def("get_bar", &Foo::get_bar
|
|---|
| 37 | , return_internal_reference<>())
|
|---|
| 38 | ;
|
|---|
| 39 | }
|
|---|
| 40 |
|
|---|
| 41 | //>>> from internal_refs import *
|
|---|
| 42 | //>>> f = Foo(3)
|
|---|
| 43 | //>>> b1 = f.get_bar()
|
|---|
| 44 | //>>> b2 = f.get_bar()
|
|---|
| 45 | //>>> b1.get_x()
|
|---|
| 46 | //3
|
|---|
| 47 | //>>> b2.get_x()
|
|---|
| 48 | //3
|
|---|
| 49 | //>>> b1.set_x(42)
|
|---|
| 50 | //>>> b2.get_x()
|
|---|
| 51 | //42
|
|---|
| 52 |
|
|---|