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.

58 lines
1.8 KiB

8 years ago
  1. /*
  2. tests/test_modules.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 "pybind11_tests.h"
  9. #include "constructor_stats.h"
  10. std::string submodule_func() {
  11. return "submodule_func()";
  12. }
  13. class A {
  14. public:
  15. A(int v) : v(v) { print_created(this, v); }
  16. ~A() { print_destroyed(this); }
  17. A(const A&) { print_copy_created(this); }
  18. A& operator=(const A &copy) { print_copy_assigned(this); v = copy.v; return *this; }
  19. std::string toString() { return "A[" + std::to_string(v) + "]"; }
  20. private:
  21. int v;
  22. };
  23. class B {
  24. public:
  25. B() { print_default_created(this); }
  26. ~B() { print_destroyed(this); }
  27. B(const B&) { print_copy_created(this); }
  28. B& operator=(const B &copy) { print_copy_assigned(this); a1 = copy.a1; a2 = copy.a2; return *this; }
  29. A &get_a1() { return a1; }
  30. A &get_a2() { return a2; }
  31. A a1{1};
  32. A a2{2};
  33. };
  34. test_initializer modules([](py::module &m) {
  35. py::module m_sub = m.def_submodule("submodule");
  36. m_sub.def("submodule_func", &submodule_func);
  37. py::class_<A>(m_sub, "A")
  38. .def(py::init<int>())
  39. .def("__repr__", &A::toString);
  40. py::class_<B>(m_sub, "B")
  41. .def(py::init<>())
  42. .def("get_a1", &B::get_a1, "Return the internal A 1", py::return_value_policy::reference_internal)
  43. .def("get_a2", &B::get_a2, "Return the internal A 2", py::return_value_policy::reference_internal)
  44. .def_readwrite("a1", &B::a1) // def_readonly uses an internal reference return policy by default
  45. .def_readwrite("a2", &B::a2);
  46. m.attr("OD") = py::module::import("collections").attr("OrderedDict");
  47. });