test_modules.cpp revision 11986:c12e4625ab56
18673SN/A/*
28673SN/A    tests/test_modules.cpp -- nested modules, importing modules, and
35509SN/A                            internal references
49150SAli.Saidi@ARM.com
59150SAli.Saidi@ARM.com    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
69055Ssaidi@eecs.umich.edu
78983Snate@binkert.org    All rights reserved. Use of this source code is governed by a
85509SN/A    BSD-style license that can be found in the LICENSE file.
95723SN/A*/
105148SN/A
115850SN/A#include "pybind11_tests.h"
125850SN/A#include "constructor_stats.h"
135148SN/A
145148SN/Astd::string submodule_func() {
155148SN/A    return "submodule_func()";
165148SN/A}
175148SN/A
185148SN/Aclass A {
195148SN/Apublic:
205148SN/A    A(int v) : v(v) { print_created(this, v); }
215148SN/A    ~A() { print_destroyed(this); }
225148SN/A    A(const A&) { print_copy_created(this); }
235148SN/A    A& operator=(const A &copy) { print_copy_assigned(this); v = copy.v; return *this; }
245148SN/A    std::string toString() { return "A[" + std::to_string(v) + "]"; }
255148SN/Aprivate:
265850SN/A    int v;
275850SN/A};
285148SN/A
295148SN/Aclass B {
305148SN/Apublic:
315148SN/A    B() { print_default_created(this); }
325148SN/A    ~B() { print_destroyed(this); }
335148SN/A    B(const B&) { print_copy_created(this); }
345148SN/A    B& operator=(const B &copy) { print_copy_assigned(this); a1 = copy.a1; a2 = copy.a2; return *this; }
355148SN/A    A &get_a1() { return a1; }
365148SN/A    A &get_a2() { return a2; }
375148SN/A
385148SN/A    A a1{1};
395148SN/A    A a2{2};
405148SN/A};
415148SN/A
425148SN/Atest_initializer modules([](py::module &m) {
435148SN/A    py::module m_sub = m.def_submodule("submodule");
445148SN/A    m_sub.def("submodule_func", &submodule_func);
455148SN/A
465148SN/A    py::class_<A>(m_sub, "A")
475148SN/A        .def(py::init<int>())
485148SN/A        .def("__repr__", &A::toString);
495148SN/A
505148SN/A    py::class_<B>(m_sub, "B")
515148SN/A        .def(py::init<>())
525148SN/A        .def("get_a1", &B::get_a1, "Return the internal A 1", py::return_value_policy::reference_internal)
535148SN/A        .def("get_a2", &B::get_a2, "Return the internal A 2", py::return_value_policy::reference_internal)
545148SN/A        .def_readwrite("a1", &B::a1)  // def_readonly uses an internal reference return policy by default
555148SN/A        .def_readwrite("a2", &B::a2);
565148SN/A
575148SN/A    m.attr("OD") = py::module::import("collections").attr("OrderedDict");
585148SN/A});
595148SN/A