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.

40 lines
1.4 KiB

  1. /*
  2. tests/test_keep_alive.cpp -- keep_alive modifier (pybind11's version
  3. of Boost.Python's with_custodian_and_ward / with_custodian_and_ward_postcall)
  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. class Child {
  10. public:
  11. Child() { py::print("Allocating child."); }
  12. ~Child() { py::print("Releasing child."); }
  13. };
  14. class Parent {
  15. public:
  16. Parent() { py::print("Allocating parent."); }
  17. ~Parent() { py::print("Releasing parent."); }
  18. void addChild(Child *) { }
  19. Child *returnChild() { return new Child(); }
  20. Child *returnNullChild() { return nullptr; }
  21. };
  22. test_initializer keep_alive([](py::module &m) {
  23. py::class_<Parent>(m, "Parent")
  24. .def(py::init<>())
  25. .def("addChild", &Parent::addChild)
  26. .def("addChildKeepAlive", &Parent::addChild, py::keep_alive<1, 2>())
  27. .def("returnChild", &Parent::returnChild)
  28. .def("returnChildKeepAlive", &Parent::returnChild, py::keep_alive<1, 0>())
  29. .def("returnNullChildKeepAliveChild", &Parent::returnNullChild, py::keep_alive<1, 0>())
  30. .def("returnNullChildKeepAliveParent", &Parent::returnNullChild, py::keep_alive<0, 1>());
  31. py::class_<Child>(m, "Child")
  32. .def(py::init<>());
  33. });