You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

55 lines
1.7 KiB

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