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