blob: 57a0765c4b73c702286bad9276a81a885d66f80a [file] [log] [blame]
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001/*
2 example/example12.cpp -- overriding virtual functions from Python
3
4 Copyright (c) 2015 Wenzel Jakob <wenzel@inf.ethz.ch>
5
6 All rights reserved. Use of this source code is governed by a
7 BSD-style license that can be found in the LICENSE file.
8*/
9
10#include "example.h"
Wenzel Jakob8f4eb002015-10-15 18:13:33 +020011#include <pybind11/functional.h>
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +020012
13/* This is an example class that we'll want to be able to extend from Python */
14class Example12 {
15public:
16 Example12(int state) : state(state) {
17 cout << "Constructing Example12.." << endl;
18 }
19
20 ~Example12() {
21 cout << "Destructing Example12.." << endl;
22 }
23
24 virtual int run(int value) {
25 std::cout << "Original implementation of Example12::run(state=" << state
26 << ", value=" << value << ")" << std::endl;
27 return state + value;
28 }
29
30 virtual void pure_virtual() = 0;
31private:
32 int state;
33};
34
35/* This is a wrapper class that must be generated */
36class PyExample12 : public Example12 {
37public:
38 using Example12::Example12; /* Inherit constructors */
39
40 virtual int run(int value) {
41 /* Generate wrapping code that enables native function overloading */
Wenzel Jakobb1b71402015-10-18 16:48:30 +020042 PYBIND11_OVERLOAD(
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +020043 int, /* Return type */
44 Example12, /* Parent class */
45 run, /* Name of function */
46 value /* Argument(s) */
47 );
48 }
49
50 virtual void pure_virtual() {
Wenzel Jakobb1b71402015-10-18 16:48:30 +020051 PYBIND11_OVERLOAD_PURE(
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +020052 void, /* Return type */
53 Example12, /* Parent class */
54 pure_virtual /* Name of function */
55 /* This function has no arguments */
56 );
57 }
58};
59
60int runExample12(Example12 *ex, int value) {
61 return ex->run(value);
62}
63
64void runExample12Virtual(Example12 *ex) {
65 ex->pure_virtual();
66}
67
68void init_ex12(py::module &m) {
69 /* Important: use the wrapper type as a template
70 argument to class_<>, but use the original name
71 to denote the type */
72 py::class_<PyExample12>(m, "Example12")
73 /* Declare that 'PyExample12' is really an alias for the original type 'Example12' */
74 .alias<Example12>()
75 .def(py::init<int>())
76 /* Reference original class in function definitions */
77 .def("run", &Example12::run)
78 .def("pure_virtual", &Example12::pure_virtual);
79
80 m.def("runExample12", &runExample12);
81 m.def("runExample12Virtual", &runExample12Virtual);
82}