test_virtual_functions.cpp 15.1 KB
Newer Older
1
/*
Dean Moldovan's avatar
Dean Moldovan committed
2
    tests/test_virtual_functions.cpp -- overriding virtual functions from Python
3

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

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

Dean Moldovan's avatar
Dean Moldovan committed
10
11
#include "pybind11_tests.h"
#include "constructor_stats.h"
12
#include <pybind11/functional.h>
13
14

/* This is an example class that we'll want to be able to extend from Python */
15
class ExampleVirt  {
16
public:
17
18
19
20
    ExampleVirt(int state) : state(state) { print_created(this, state); }
    ExampleVirt(const ExampleVirt &e) : state(e.state) { print_copy_created(this); }
    ExampleVirt(ExampleVirt &&e) : state(e.state) { print_move_created(this); e.state = 0; }
    ~ExampleVirt() { print_destroyed(this); }
21
22

    virtual int run(int value) {
23
        py::print("Original implementation of "
24
                  "ExampleVirt::run(state={}, value={}, str1={}, str2={})"_s.format(state, value, get_string1(), *get_string2()));
25
26
27
        return state + value;
    }

28
    virtual bool run_bool() = 0;
29
    virtual void pure_virtual() = 0;
30
31
32
33
34
35
36

    // Returning a reference/pointer to a type converted from python (numbers, strings, etc.) is a
    // bit trickier, because the actual int& or std::string& or whatever only exists temporarily, so
    // we have to handle it specially in the trampoline class (see below).
    virtual const std::string &get_string1() { return str1; }
    virtual const std::string *get_string2() { return &str2; }

37
38
private:
    int state;
39
    const std::string str1{"default1"}, str2{"default2"};
40
41
42
};

/* This is a wrapper class that must be generated */
43
class PyExampleVirt : public ExampleVirt {
44
public:
45
    using ExampleVirt::ExampleVirt; /* Inherit constructors */
46

47
    int run(int value) override {
48
        /* Generate wrapping code that enables native function overloading */
49
        PYBIND11_OVERLOAD(
50
51
52
53
            int,         /* Return type */
            ExampleVirt, /* Parent class */
            run,         /* Name of function */
            value        /* Argument(s) */
54
55
56
        );
    }

57
    bool run_bool() override {
58
        PYBIND11_OVERLOAD_PURE(
59
            bool,         /* Return type */
60
            ExampleVirt,  /* Parent class */
61
62
63
            run_bool,     /* Name of function */
                          /* This function has no arguments. The trailing comma
                             in the previous line is needed for some compilers */
64
65
66
        );
    }

67
    void pure_virtual() override {
68
        PYBIND11_OVERLOAD_PURE(
69
            void,         /* Return type */
70
            ExampleVirt,  /* Parent class */
71
72
73
            pure_virtual, /* Name of function */
                          /* This function has no arguments. The trailing comma
                             in the previous line is needed for some compilers */
74
75
        );
    }
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96

    // We can return reference types for compatibility with C++ virtual interfaces that do so, but
    // note they have some significant limitations (see the documentation).
    const std::string &get_string1() override {
        PYBIND11_OVERLOAD(
            const std::string &, /* Return type */
            ExampleVirt,         /* Parent class */
            get_string1,         /* Name of function */
                                 /* (no arguments) */
        );
    }

    const std::string *get_string2() override {
        PYBIND11_OVERLOAD(
            const std::string *, /* Return type */
            ExampleVirt,         /* Parent class */
            get_string2,         /* Name of function */
                                 /* (no arguments) */
        );
    }

97
98
};

99
100
class NonCopyable {
public:
101
102
    NonCopyable(int a, int b) : value{new int(a*b)} { print_created(this, a, b); }
    NonCopyable(NonCopyable &&o) { value = std::move(o.value); print_move_created(this); }
103
104
105
106
107
108
109
    NonCopyable(const NonCopyable &) = delete;
    NonCopyable() = delete;
    void operator=(const NonCopyable &) = delete;
    void operator=(NonCopyable &&) = delete;
    std::string get_value() const {
        if (value) return std::to_string(*value); else return "(null)";
    }
110
    ~NonCopyable() { print_destroyed(this); }
111
112
113
114
115
116
117
118
119

private:
    std::unique_ptr<int> value;
};

// This is like the above, but is both copy and movable.  In effect this means it should get moved
// when it is not referenced elsewhere, but copied if it is still referenced.
class Movable {
public:
120
121
122
    Movable(int a, int b) : value{a+b} { print_created(this, a, b); }
    Movable(const Movable &m) { value = m.value; print_copy_created(this); }
    Movable(Movable &&m) { value = std::move(m.value); print_move_created(this); }
123
    std::string get_value() const { return std::to_string(value); }
124
    ~Movable() { print_destroyed(this); }
125
126
127
128
129
130
131
132
133
private:
    int value;
};

class NCVirt {
public:
    virtual NonCopyable get_noncopyable(int a, int b) { return NonCopyable(a, b); }
    virtual Movable get_movable(int a, int b) = 0;

134
135
    std::string print_nc(int a, int b) { return get_noncopyable(a, b).get_value(); }
    std::string print_movable(int a, int b) { return get_movable(a, b).get_value(); }
136
137
};
class NCVirtTrampoline : public NCVirt {
138
#if !defined(__INTEL_COMPILER)
139
    NonCopyable get_noncopyable(int a, int b) override {
140
141
        PYBIND11_OVERLOAD(NonCopyable, NCVirt, get_noncopyable, a, b);
    }
142
#endif
143
    Movable get_movable(int a, int b) override {
144
145
146
147
        PYBIND11_OVERLOAD_PURE(Movable, NCVirt, get_movable, a, b);
    }
};

148
int runExampleVirt(ExampleVirt *ex, int value) {
149
150
151
    return ex->run(value);
}

152
bool runExampleVirtBool(ExampleVirt* ex) {
153
154
155
    return ex->run_bool();
}

156
void runExampleVirtVirtual(ExampleVirt *ex) {
157
158
159
    ex->pure_virtual();
}

160

161
162
// Inheriting virtual methods.  We do two versions here: the repeat-everything version and the
// templated trampoline versions mentioned in docs/advanced.rst.
163
//
164
165
166
// These base classes are exactly the same, 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
167
168
169
170
171
// multiple python classes).
class A_Repeat {
#define A_METHODS \
public: \
    virtual int unlucky_number() = 0; \
172
173
174
175
176
    virtual std::string say_something(unsigned times) { \
        std::string s = ""; \
        for (unsigned i = 0; i < times; ++i) \
            s += "hi"; \
        return s; \
177
178
179
    } \
    std::string say_everything() { \
        return say_something(1) + " " + std::to_string(unlucky_number()); \
180
181
182
183
184
185
186
    }
A_METHODS
};
class B_Repeat : public A_Repeat {
#define B_METHODS \
public: \
    int unlucky_number() override { return 13; } \
187
188
    std::string say_something(unsigned times) override { \
        return "B says hi " + std::to_string(times) + " times"; \
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
    } \
    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 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, ); }
217
    std::string say_something(unsigned times) override { PYBIND11_OVERLOAD(std::string, A_Repeat, say_something, times); }
218
219
220
221
222
};
class PyB_Repeat : public B_Repeat {
public:
    using B_Repeat::B_Repeat;
    int unlucky_number() override { PYBIND11_OVERLOAD(int, B_Repeat, unlucky_number, ); }
223
    std::string say_something(unsigned times) override { PYBIND11_OVERLOAD(std::string, B_Repeat, say_something, times); }
224
225
226
227
228
229
    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, ); }
230
    std::string say_something(unsigned times) override { PYBIND11_OVERLOAD(std::string, C_Repeat, say_something, times); }
231
232
233
234
235
236
    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, ); }
237
    std::string say_something(unsigned times) override { PYBIND11_OVERLOAD(std::string, D_Repeat, say_something, times); }
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
    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, ); }
260
    std::string say_something(unsigned times) override { PYBIND11_OVERLOAD(std::string, Base, say_something, times); }
261
262
263
264
265
266
};
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, ); }
Wenzel Jakob's avatar
Wenzel Jakob committed
267
    double lucky_number() override { PYBIND11_OVERLOAD(double, Base, lucky_number, ); }
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
};
// 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;
};
*/


void initialize_inherited_virtuals(py::module &m) {
    // Method 1: repeat
285
    py::class_<A_Repeat, PyA_Repeat>(m, "A_Repeat")
286
287
        .def(py::init<>())
        .def("unlucky_number", &A_Repeat::unlucky_number)
288
289
        .def("say_something", &A_Repeat::say_something)
        .def("say_everything", &A_Repeat::say_everything);
290
    py::class_<B_Repeat, A_Repeat, PyB_Repeat>(m, "B_Repeat")
291
292
        .def(py::init<>())
        .def("lucky_number", &B_Repeat::lucky_number);
293
    py::class_<C_Repeat, B_Repeat, PyC_Repeat>(m, "C_Repeat")
294
        .def(py::init<>());
295
    py::class_<D_Repeat, C_Repeat, PyD_Repeat>(m, "D_Repeat")
296
297
298
        .def(py::init<>());

    // Method 2: Templated trampolines
299
    py::class_<A_Tpl, PyA_Tpl<>>(m, "A_Tpl")
300
301
        .def(py::init<>())
        .def("unlucky_number", &A_Tpl::unlucky_number)
302
303
        .def("say_something", &A_Tpl::say_something)
        .def("say_everything", &A_Tpl::say_everything);
304
    py::class_<B_Tpl, A_Tpl, PyB_Tpl<>>(m, "B_Tpl")
305
306
        .def(py::init<>())
        .def("lucky_number", &B_Tpl::lucky_number);
307
    py::class_<C_Tpl, B_Tpl, PyB_Tpl<C_Tpl>>(m, "C_Tpl")
308
        .def(py::init<>());
309
    py::class_<D_Tpl, C_Tpl, PyB_Tpl<D_Tpl>>(m, "D_Tpl")
310
311
312
313
        .def(py::init<>());

};

314
315
316
317
318
319
320
321
322
323
struct Base {
    /* for some reason MSVC2015 can't compile this if the function is pure virtual */
    virtual std::string dispatch() const { return {}; };
};

struct DispatchIssue : Base {
    virtual std::string dispatch() const {
        PYBIND11_OVERLOAD_PURE(std::string, Base, dispatch, /* no arguments */);
    }
};
324

325
test_initializer virtual_functions([](py::module &m) {
326
    py::class_<ExampleVirt, PyExampleVirt>(m, "ExampleVirt")
327
328
        .def(py::init<int>())
        /* Reference original class in function definitions */
329
330
331
        .def("run", &ExampleVirt::run)
        .def("run_bool", &ExampleVirt::run_bool)
        .def("pure_virtual", &ExampleVirt::pure_virtual);
332

333
    py::class_<NonCopyable>(m, "NonCopyable")
334
335
        .def(py::init<int, int>());

336
    py::class_<Movable>(m, "Movable")
337
338
339
        .def(py::init<int, int>());

#if !defined(__INTEL_COMPILER)
340
    py::class_<NCVirt, NCVirtTrampoline>(m, "NCVirt")
341
342
343
344
        .def(py::init<>())
        .def("get_noncopyable", &NCVirt::get_noncopyable)
        .def("get_movable", &NCVirt::get_movable)
        .def("print_nc", &NCVirt::print_nc)
345
346
        .def("print_movable", &NCVirt::print_movable);
#endif
347

348
349
350
    m.def("runExampleVirt", &runExampleVirt);
    m.def("runExampleVirtBool", &runExampleVirtBool);
    m.def("runExampleVirtVirtual", &runExampleVirtVirtual);
351

352
    m.def("cstats_debug", &ConstructorStats::get<ExampleVirt>);
353
    initialize_inherited_virtuals(m);
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400

    // #159: virtual function dispatch has problems with similar-named functions
    py::class_<Base, DispatchIssue>(m, "DispatchIssue")
        .def(py::init<>())
        .def("dispatch", &Base::dispatch);

    m.def("dispatch_issue_go", [](const Base * b) { return b->dispatch(); });

    // #392/397: overridding reference-returning functions
    class OverrideTest {
    public:
        struct A { std::string value = "hi"; };
        std::string v;
        A a;
        explicit OverrideTest(const std::string &v) : v{v} {}
        virtual std::string str_value() { return v; }
        virtual std::string &str_ref() { return v; }
        virtual A A_value() { return a; }
        virtual A &A_ref() { return a; }
    };

    class PyOverrideTest : public OverrideTest {
    public:
        using OverrideTest::OverrideTest;
        std::string str_value() override { PYBIND11_OVERLOAD(std::string, OverrideTest, str_value); }
        // Not allowed (uncommenting should hit a static_assert failure): we can't get a reference
        // to a python numeric value, since we only copy values in the numeric type caster:
//      std::string &str_ref() override { PYBIND11_OVERLOAD(std::string &, OverrideTest, str_ref); }
        // But we can work around it like this:
    private:
        std::string _tmp;
        std::string str_ref_helper() { PYBIND11_OVERLOAD(std::string, OverrideTest, str_ref); }
    public:
        std::string &str_ref() override { return _tmp = str_ref_helper(); }

        A A_value() override { PYBIND11_OVERLOAD(A, OverrideTest, A_value); }
        A &A_ref() override { PYBIND11_OVERLOAD(A &, OverrideTest, A_ref); }
    };

    py::class_<OverrideTest::A>(m, "OverrideTest_A")
        .def_readwrite("value", &OverrideTest::A::value);
    py::class_<OverrideTest, PyOverrideTest>(m, "OverrideTest")
        .def(py::init<const std::string &>())
        .def("str_value", &OverrideTest::str_value)
//      .def("str_ref", &OverrideTest::str_ref)
        .def("A_value", &OverrideTest::A_value)
        .def("A_ref", &OverrideTest::A_ref);
401
});