blob: cd62a02e884184b190cdcd9221390014cb26572c [file] [log] [blame]
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001/*
Dean Moldovana0c1ccf2016-08-12 13:50:00 +02002 tests/test_keep_alive.cpp -- keep_alive modifier (pybind11's version
Wenzel Jakob5f218b32016-01-17 22:36:39 +01003 of Boost.Python's with_custodian_and_ward / with_custodian_and_ward_postcall)
4
Wenzel Jakob8cb6cb32016-04-17 20:21:41 +02005 Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
Wenzel Jakob5f218b32016-01-17 22:36:39 +01006
7 All rights reserved. Use of this source code is governed by a
8 BSD-style license that can be found in the LICENSE file.
9*/
10
Dean Moldovana0c1ccf2016-08-12 13:50:00 +020011#include "pybind11_tests.h"
Wenzel Jakob5f218b32016-01-17 22:36:39 +010012
13class Child {
14public:
Dean Moldovan81511be2016-09-07 00:50:10 +020015 Child() { py::print("Allocating child."); }
16 ~Child() { py::print("Releasing child."); }
Wenzel Jakob5f218b32016-01-17 22:36:39 +010017};
18
19class Parent {
20public:
Dean Moldovan81511be2016-09-07 00:50:10 +020021 Parent() { py::print("Allocating parent."); }
22 ~Parent() { py::print("Releasing parent."); }
Wenzel Jakob5f218b32016-01-17 22:36:39 +010023 void addChild(Child *) { }
24 Child *returnChild() { return new Child(); }
Glen Walkerf45bb582016-08-16 17:50:43 +120025 Child *returnNullChild() { return nullptr; }
Wenzel Jakob5f218b32016-01-17 22:36:39 +010026};
27
Jason Rhinelander52f4be82016-09-03 14:54:22 -040028test_initializer keep_alive([](py::module &m) {
Wenzel Jakob5f218b32016-01-17 22:36:39 +010029 py::class_<Parent>(m, "Parent")
30 .def(py::init<>())
31 .def("addChild", &Parent::addChild)
32 .def("addChildKeepAlive", &Parent::addChild, py::keep_alive<1, 2>())
33 .def("returnChild", &Parent::returnChild)
Glen Walkerf45bb582016-08-16 17:50:43 +120034 .def("returnChildKeepAlive", &Parent::returnChild, py::keep_alive<1, 0>())
35 .def("returnNullChildKeepAliveChild", &Parent::returnNullChild, py::keep_alive<1, 0>())
36 .def("returnNullChildKeepAliveParent", &Parent::returnNullChild, py::keep_alive<0, 1>());
Wenzel Jakob5f218b32016-01-17 22:36:39 +010037
38 py::class_<Child>(m, "Child")
39 .def(py::init<>());
Jason Rhinelander52f4be82016-09-03 14:54:22 -040040});