example-virtual-functions.cpp 12.2 KB
Newer Older
1
/*
2
    example/example-virtual-functions.cpp -- overriding virtual functions from Python
3

4
    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
5
6
7
8
9
10

    All rights reserved. Use of this source code is governed by a
    BSD-style license that can be found in the LICENSE file.
*/

#include "example.h"
11
#include <pybind11/functional.h>
12
13

/* This is an example class that we'll want to be able to extend from Python */
14
class ExampleVirt  {
15
public:
16
17
    ExampleVirt(int state) : state(state) {
        cout << "Constructing ExampleVirt.." << endl;
18
19
    }

20
21
    ~ExampleVirt() {
        cout << "Destructing ExampleVirt.." << endl;
22
23
24
    }

    virtual int run(int value) {
25
        std::cout << "Original implementation of ExampleVirt::run(state=" << state
26
27
28
29
                  << ", value=" << value << ")" << std::endl;
        return state + value;
    }

30
    virtual bool run_bool() = 0;
31
32
33
34
35
36
    virtual void pure_virtual() = 0;
private:
    int state;
};

/* This is a wrapper class that must be generated */
37
class PyExampleVirt : public ExampleVirt {
38
public:
39
    using ExampleVirt::ExampleVirt; /* Inherit constructors */
40
41
42

    virtual int run(int value) {
        /* Generate wrapping code that enables native function overloading */
43
        PYBIND11_OVERLOAD(
44
45
46
47
            int,         /* Return type */
            ExampleVirt, /* Parent class */
            run,         /* Name of function */
            value        /* Argument(s) */
48
49
50
        );
    }

51
52
    virtual bool run_bool() {
        PYBIND11_OVERLOAD_PURE(
53
            bool,         /* Return type */
54
            ExampleVirt,  /* Parent class */
55
56
57
            run_bool,     /* Name of function */
                          /* This function has no arguments. The trailing comma
                             in the previous line is needed for some compilers */
58
59
60
        );
    }

61
    virtual void pure_virtual() {
62
        PYBIND11_OVERLOAD_PURE(
63
            void,         /* Return type */
64
            ExampleVirt,  /* Parent class */
65
66
67
            pure_virtual, /* Name of function */
                          /* This function has no arguments. The trailing comma
                             in the previous line is needed for some compilers */
68
69
70
71
        );
    }
};

72
int runExampleVirt(ExampleVirt *ex, int value) {
73
74
75
    return ex->run(value);
}

76
bool runExampleVirtBool(ExampleVirt* ex) {
77
78
79
    return ex->run_bool();
}

80
void runExampleVirtVirtual(ExampleVirt *ex) {
81
82
83
    ex->pure_virtual();
}

84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284

// Inheriting virtual methods.  We do three versions here: the repeat-everything version and the
// templated trampoline versions mentioned in docs/advanced.rst, and also another version using
// multiple inheritance.
//
// This latter approach has the advantage of generating substantially less code for deep
// hierarchies, but it requires intrusive changes of changing the wrapped classes to using virtual
// inheritance, which itself requires constructor rewriting for any non-default virtual base class
// constructors (most problematic is that constructors cannot be effectively inherited from a
// virtual base class).  The example is kept here because it does work, and may be useful in limited
// cases, but the non-instrusive templated version is generally preferred.
//
// These base classes are all exactly the same (aside from the virtual inheritance for the MI
// version), but we technically need distinct classes for this example code because we need to be
// able to bind them properly (pybind11, sensibly, doesn't allow us to bind the same C++ class to
// multiple python classes).
class A_Repeat {
#define A_METHODS \
public: \
    virtual int unlucky_number() = 0; \
    virtual void say_something(unsigned times) { \
        for (unsigned i = 0; i < times; i++) std::cout << "hi"; \
        std::cout << std::endl; \
    }
A_METHODS
};
class B_Repeat : public A_Repeat {
#define B_METHODS \
public: \
    int unlucky_number() override { return 13; } \
    void say_something(unsigned times) override { \
        std::cout << "B says hi " << times << " times" << std::endl; \
    } \
    virtual double lucky_number() { return 7.0; }
B_METHODS
};
class C_Repeat : public B_Repeat {
#define C_METHODS \
public: \
    int unlucky_number() override { return 4444; } \
    double lucky_number() override { return 888; }
C_METHODS
};
class D_Repeat : public C_Repeat {
#define D_METHODS // Nothing overridden.
D_METHODS
};

// Base classes for multiple inheritance trampolines; note the added "virtual" inheritance.  The
// classes are otherwise identical.
class A_MI { A_METHODS };
class B_MI : virtual public A_MI { B_METHODS };
class C_MI : virtual public B_MI { C_METHODS };
class D_MI : virtual public C_MI { D_METHODS };

// Base classes for templated inheritance trampolines.  Identical to the repeat-everything version:
class A_Tpl { A_METHODS };
class B_Tpl : public A_Tpl { B_METHODS };
class C_Tpl : public B_Tpl { C_METHODS };
class D_Tpl : public C_Tpl { D_METHODS };


// Inheritance approach 1: each trampoline gets every virtual method (11 in total)
class PyA_Repeat : public A_Repeat {
public:
    using A_Repeat::A_Repeat;
    int unlucky_number() override { PYBIND11_OVERLOAD_PURE(int, A_Repeat, unlucky_number, ); }
    void say_something(unsigned times) override { PYBIND11_OVERLOAD(void, A_Repeat, say_something, times); }
};
class PyB_Repeat : public B_Repeat {
public:
    using B_Repeat::B_Repeat;
    int unlucky_number() override { PYBIND11_OVERLOAD(int, B_Repeat, unlucky_number, ); }
    void say_something(unsigned times) override { PYBIND11_OVERLOAD(void, B_Repeat, say_something, times); }
    double lucky_number() override { PYBIND11_OVERLOAD(double, B_Repeat, lucky_number, ); }
};
class PyC_Repeat : public C_Repeat {
public:
    using C_Repeat::C_Repeat;
    int unlucky_number() override { PYBIND11_OVERLOAD(int, C_Repeat, unlucky_number, ); }
    void say_something(unsigned times) override { PYBIND11_OVERLOAD(void, C_Repeat, say_something, times); }
    double lucky_number() override { PYBIND11_OVERLOAD(double, C_Repeat, lucky_number, ); }
};
class PyD_Repeat : public D_Repeat {
public:
    using D_Repeat::D_Repeat;
    int unlucky_number() override { PYBIND11_OVERLOAD(int, D_Repeat, unlucky_number, ); }
    void say_something(unsigned times) override { PYBIND11_OVERLOAD(void, D_Repeat, say_something, times); }
    double lucky_number() override { PYBIND11_OVERLOAD(double, D_Repeat, lucky_number, ); }
};

// Inheritance approach 2: templated trampoline classes.
//
// Advantages:
// - we have only 2 (template) class and 4 method declarations (one per virtual method, plus one for
//   any override of a pure virtual method), versus 4 classes and 6 methods (MI) or 4 classes and 11
//   methods (repeat).
// - Compared to MI, we also don't have to change the non-trampoline inheritance to virtual, and can
//   properly inherit constructors.
//
// Disadvantage:
// - the compiler must still generate and compile 14 different methods (more, even, than the 11
//   required for the repeat approach) instead of the 6 required for MI.  (If there was no pure
//   method (or no pure method override), the number would drop down to the same 11 as the repeat
//   approach).
template <class Base = A_Tpl>
class PyA_Tpl : public Base {
public:
    using Base::Base; // Inherit constructors
    int unlucky_number() override { PYBIND11_OVERLOAD_PURE(int, Base, unlucky_number, ); }
    void say_something(unsigned times) override { PYBIND11_OVERLOAD(void, Base, say_something, times); }
};
template <class Base = B_Tpl>
class PyB_Tpl : public PyA_Tpl<Base> {
public:
    using PyA_Tpl<Base>::PyA_Tpl; // Inherit constructors (via PyA_Tpl's inherited constructors)
    int unlucky_number() override { PYBIND11_OVERLOAD(int, Base, unlucky_number, ); }
    double lucky_number() { PYBIND11_OVERLOAD(double, Base, lucky_number, ); }
};
// Since C_Tpl and D_Tpl don't declare any new virtual methods, we don't actually need these (we can
// use PyB_Tpl<C_Tpl> and PyB_Tpl<D_Tpl> for the trampoline classes instead):
/*
template <class Base = C_Tpl> class PyC_Tpl : public PyB_Tpl<Base> {
public:
    using PyB_Tpl<Base>::PyB_Tpl;
};
template <class Base = D_Tpl> class PyD_Tpl : public PyC_Tpl<Base> {
public:
    using PyC_Tpl<Base>::PyC_Tpl;
};
*/

// Inheritance approach 3: multiple inheritance with virtual base class inheritance.  This requires
// declaration and compilation of exactly 7 methods (one per virtual method declaration or
// override), versus the 11 required above.  On the other hand, if we need anything other than
// default constructors, this quickly becomes painful, and so this is of limited use.
class PyA_MI : virtual public A_MI {
public:
    // Can't inherit constructors: we would have to duplicate constructors with an explicit
    // initializer for each virtual base, which is a pain for anything but the default constructor.
    int unlucky_number() override { PYBIND11_OVERLOAD_PURE(int, A_MI, unlucky_number, ); }
    void say_something(unsigned times) override { PYBIND11_OVERLOAD(void, A_MI, say_something, times); }
};
class PyB_MI : public PyA_MI, virtual public B_MI {
public:
    void say_something(unsigned times) override { PYBIND11_OVERLOAD(void, B_MI, say_something, times); }
    double lucky_number() { PYBIND11_OVERLOAD(double, B_MI, lucky_number, ); }
    int unlucky_number() { PYBIND11_OVERLOAD(int, B_MI, unlucky_number, ); }
};
class PyC_MI : public PyB_MI, virtual public C_MI {
public:
    int unlucky_number() override { PYBIND11_OVERLOAD(int, C_MI, unlucky_number, ); }
    double lucky_number() override { PYBIND11_OVERLOAD(double, C_MI, lucky_number, ); }
};
class PyD_MI : public PyC_MI, virtual public D_MI {
};


void initialize_inherited_virtuals(py::module &m) {
    // Method 1: repeat
    py::class_<A_Repeat, std::unique_ptr<A_Repeat>, PyA_Repeat>(m, "A_Repeat")
        .def(py::init<>())
        .def("unlucky_number", &A_Repeat::unlucky_number)
        .def("say_something", &A_Repeat::say_something);
    py::class_<B_Repeat, std::unique_ptr<B_Repeat>, PyB_Repeat>(m, "B_Repeat", py::base<A_Repeat>())
        .def(py::init<>())
        .def("lucky_number", &B_Repeat::lucky_number);
    py::class_<C_Repeat, std::unique_ptr<C_Repeat>, PyC_Repeat>(m, "C_Repeat", py::base<B_Repeat>())
        .def(py::init<>());
    py::class_<D_Repeat, std::unique_ptr<D_Repeat>, PyD_Repeat>(m, "D_Repeat", py::base<C_Repeat>())
        .def(py::init<>());

    // Method 2: Templated trampolines
    py::class_<A_Tpl, std::unique_ptr<A_Tpl>, PyA_Tpl<>>(m, "A_Tpl")
        .def(py::init<>())
        .def("unlucky_number", &A_Tpl::unlucky_number)
        .def("say_something", &A_Tpl::say_something);
    py::class_<B_Tpl, std::unique_ptr<B_Tpl>, PyB_Tpl<>>(m, "B_Tpl", py::base<A_Tpl>())
        .def(py::init<>())
        .def("lucky_number", &B_Tpl::lucky_number);
    py::class_<C_Tpl, std::unique_ptr<C_Tpl>, PyB_Tpl<C_Tpl>>(m, "C_Tpl", py::base<B_Tpl>())
        .def(py::init<>());
    py::class_<D_Tpl, std::unique_ptr<D_Tpl>, PyB_Tpl<D_Tpl>>(m, "D_Tpl", py::base<C_Tpl>())
        .def(py::init<>());

    // Method 3: MI
    py::class_<A_MI, std::unique_ptr<A_MI>, PyA_MI>(m, "A_MI")
        .def(py::init<>())
        .def("unlucky_number", &A_MI::unlucky_number)
        .def("say_something", &A_MI::say_something);
    py::class_<B_MI, std::unique_ptr<B_MI>, PyB_MI>(m, "B_MI", py::base<A_MI>())
        .def(py::init<>())
        .def("lucky_number", &B_MI::lucky_number);
    py::class_<C_MI, std::unique_ptr<C_MI>, PyC_MI>(m, "C_MI", py::base<B_MI>())
        .def(py::init<>());
    py::class_<D_MI, std::unique_ptr<D_MI>, PyD_MI>(m, "D_MI", py::base<C_MI>())
        .def(py::init<>());

};


285
286
void init_ex_virtual_functions(py::module &m) {
    /* Important: indicate the trampoline class PyExampleVirt using the third
287
288
       argument to py::class_. The second argument with the unique pointer
       is simply the default holder type used by pybind11. */
289
    py::class_<ExampleVirt, std::unique_ptr<ExampleVirt>, PyExampleVirt>(m, "ExampleVirt")
290
291
        .def(py::init<int>())
        /* Reference original class in function definitions */
292
293
294
        .def("run", &ExampleVirt::run)
        .def("run_bool", &ExampleVirt::run_bool)
        .def("pure_virtual", &ExampleVirt::pure_virtual);
295

296
297
298
    m.def("runExampleVirt", &runExampleVirt);
    m.def("runExampleVirtBool", &runExampleVirtBool);
    m.def("runExampleVirtVirtual", &runExampleVirtVirtual);
299
300

    initialize_inherited_virtuals(m);
301
}