blob: 81b6edc0932815731b0deaded8091c0ec0500e60 [file] [log] [blame]
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001/*
Wenzel Jakoba576e6a2015-07-29 17:51:54 +02002 example/example9.cpp -- nested modules and internal references
Wenzel Jakob38bd7112015-07-05 20:05:44 +02003
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
12void submodule_func() {
13 std::cout << "submodule_func()" << std::endl;
14}
15
16class A {
17public:
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) + "]"; }
22private:
23 int v;
24};
25
26class B {
27public:
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
38void 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}