Wenzel Jakob | 38bd711 | 2015-07-05 20:05:44 +0200 | [diff] [blame] | 1 | /* |
Wenzel Jakob | a576e6a | 2015-07-29 17:51:54 +0200 | [diff] [blame] | 2 | example/example9.cpp -- nested modules and internal references |
Wenzel Jakob | 38bd711 | 2015-07-05 20:05:44 +0200 | [diff] [blame] | 3 | |
| 4 | Copyright (c) 2015 Wenzel Jakob <wenzel@inf.ethz.ch> |
| 5 | |
| 6 | All rights reserved. Use of this source code is governed by a |
| 7 | BSD-style license that can be found in the LICENSE file. |
| 8 | */ |
| 9 | |
| 10 | #include "example.h" |
| 11 | |
| 12 | void submodule_func() { |
| 13 | std::cout << "submodule_func()" << std::endl; |
| 14 | } |
| 15 | |
| 16 | class A { |
| 17 | public: |
| 18 | A(int v) : v(v) { std::cout << "A constructor" << std::endl; } |
| 19 | ~A() { std::cout << "A destructor" << std::endl; } |
| 20 | A(const A&) { std::cout << "A copy constructor" << std::endl; } |
| 21 | std::string toString() { return "A[" + std::to_string(v) + "]"; } |
| 22 | private: |
| 23 | int v; |
| 24 | }; |
| 25 | |
| 26 | class B { |
| 27 | public: |
| 28 | B() { std::cout << "B constructor" << std::endl; } |
| 29 | ~B() { std::cout << "B destructor" << std::endl; } |
| 30 | B(const B&) { std::cout << "B copy constructor" << std::endl; } |
| 31 | A &get_a1() { return a1; } |
| 32 | A &get_a2() { return a2; } |
| 33 | |
| 34 | A a1{1}; |
| 35 | A a2{2}; |
| 36 | }; |
| 37 | |
| 38 | void init_ex9(py::module &m) { |
| 39 | py::module m_sub = m.def_submodule("submodule"); |
| 40 | m_sub.def("submodule_func", &submodule_func); |
| 41 | |
| 42 | py::class_<A>(m_sub, "A") |
| 43 | .def(py::init<int>()) |
| 44 | .def("__repr__", &A::toString); |
| 45 | |
| 46 | py::class_<B>(m_sub, "B") |
| 47 | .def(py::init<>()) |
| 48 | .def("get_a1", &B::get_a1, "Return the internal A 1", py::return_value_policy::reference_internal) |
| 49 | .def("get_a2", &B::get_a2, "Return the internal A 2", py::return_value_policy::reference_internal) |
| 50 | .def_readwrite("a1", &B::a1) // def_readonly uses an internal reference return policy by default |
| 51 | .def_readwrite("a2", &B::a2); |
| 52 | } |