blob: 7d617793dcccb0344dc78dbe6a0e303933d5c474 [file] [log] [blame]
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001/*
2 example/example5.cpp -- Example 5: inheritance, callbacks, acquiring
3 and releasing the global interpreter lock
4
5 Copyright (c) 2015 Wenzel Jakob <wenzel@inf.ethz.ch>
6
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
11#include "example.h"
12
13
14class Pet {
15public:
16 Pet(const std::string &name, const std::string &species)
17 : m_name(name), m_species(species) {}
18 std::string name() const { return m_name; }
19 std::string species() const { return m_species; }
20private:
21 std::string m_name;
22 std::string m_species;
23};
24
25class Dog : public Pet {
26public:
27 Dog(const std::string &name) : Pet(name, "dog") {}
28 void bark() const { std::cout << "Woof!" << std::endl; }
29};
30
31void pet_print(const Pet &pet) {
32 std::cout << pet.name() + " is a " + pet.species() << std::endl;
33}
34
35void dog_bark(const Dog &dog) {
36 dog.bark();
37}
38
39class Example5 {
40public:
41 Example5(py::handle self, int state)
42 : self(self), state(state) {
43 cout << "Constructing Example5.." << endl;
44 }
45
46 ~Example5() {
47 cout << "Destructing Example5.." << endl;
48 }
49
50 void callback(int value) {
51 py::gil_scoped_acquire gil;
52 cout << "In Example5::callback() " << endl;
53 py::object method = self.attr("callback");
54 method.call(state, value);
55 }
56private:
57 py::handle self;
58 int state;
59};
60
61bool test_callback1(py::object func) {
62 func.call();
63 return false;
64}
65
66int test_callback2(py::object func) {
67 py::object result = func.call("Hello", true, 5);
68 return result.cast<int>();
69}
70
71void test_callback3(Example5 *ex, int value) {
72 py::gil_scoped_release gil;
73 ex->callback(value);
74}
75
76void init_ex5(py::module &m) {
77 py::class_<Pet> pet_class(m, "Pet");
78 pet_class
79 .def(py::init<std::string, std::string>())
80 .def("name", &Pet::name)
81 .def("species", &Pet::species);
82
83 py::class_<Dog>(m, "Dog", pet_class)
84 .def(py::init<std::string>());
85
86 m.def("pet_print", pet_print);
87 m.def("dog_bark", dog_bark);
88
89 m.def("test_callback1", &test_callback1);
90 m.def("test_callback2", &test_callback2);
91 m.def("test_callback3", &test_callback3);
92
93 py::class_<Example5>(m, "Example5")
94 .def(py::init<py::object, int>());
95}