test_virtual_functions.cpp revision 11986:c12e4625ab56
1/* 2 tests/test_virtual_functions.cpp -- overriding virtual functions from Python 3 4 Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.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 "pybind11_tests.h" 11#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 */ 15class ExampleVirt { 16public: 17 ExampleVirt(int state) : state(state) { print_created(this, state); } 18 ExampleVirt(const ExampleVirt &e) : state(e.state) { print_copy_created(this); } 19 ExampleVirt(ExampleVirt &&e) : state(e.state) { print_move_created(this); e.state = 0; } 20 ~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 return state + value; 26 } 27 28 virtual bool run_bool() = 0; 29 virtual void pure_virtual() = 0; 30 31 // Returning a reference/pointer to a type converted from python (numbers, strings, etc.) is a 32 // bit trickier, because the actual int& or std::string& or whatever only exists temporarily, so 33 // we have to handle it specially in the trampoline class (see below). 34 virtual const std::string &get_string1() { return str1; } 35 virtual const std::string *get_string2() { return &str2; } 36 37private: 38 int state; 39 const std::string str1{"default1"}, str2{"default2"}; 40}; 41 42/* This is a wrapper class that must be generated */ 43class PyExampleVirt : public ExampleVirt { 44public: 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 int, /* Return type */ 51 ExampleVirt, /* Parent class */ 52 run, /* Name of function */ 53 value /* Argument(s) */ 54 ); 55 } 56 57 bool run_bool() override { 58 PYBIND11_OVERLOAD_PURE( 59 bool, /* Return type */ 60 ExampleVirt, /* Parent class */ 61 run_bool, /* Name of function */ 62 /* This function has no arguments. The trailing comma 63 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 pure_virtual, /* Name of function */ 72 /* This function has no arguments. The trailing comma 73 in the previous line is needed for some compilers */ 74 ); 75 } 76 77 // We can return reference types for compatibility with C++ virtual interfaces that do so, but 78 // note they have some significant limitations (see the documentation). 79 const std::string &get_string1() override { 80 PYBIND11_OVERLOAD( 81 const std::string &, /* Return type */ 82 ExampleVirt, /* Parent class */ 83 get_string1, /* Name of function */ 84 /* (no arguments) */ 85 ); 86 } 87 88 const std::string *get_string2() override { 89 PYBIND11_OVERLOAD( 90 const std::string *, /* Return type */ 91 ExampleVirt, /* Parent class */ 92 get_string2, /* Name of function */ 93 /* (no arguments) */ 94 ); 95 } 96 97}; 98 99class NonCopyable { 100public: 101 NonCopyable(int a, int b) : value{new int(a*b)} { print_created(this, a, b); } 102 NonCopyable(NonCopyable &&o) { value = std::move(o.value); print_move_created(this); } 103 NonCopyable(const NonCopyable &) = delete; 104 NonCopyable() = delete; 105 void operator=(const NonCopyable &) = delete; 106 void operator=(NonCopyable &&) = delete; 107 std::string get_value() const { 108 if (value) return std::to_string(*value); else return "(null)"; 109 } 110 ~NonCopyable() { print_destroyed(this); } 111 112private: 113 std::unique_ptr<int> value; 114}; 115 116// This is like the above, but is both copy and movable. In effect this means it should get moved 117// when it is not referenced elsewhere, but copied if it is still referenced. 118class Movable { 119public: 120 Movable(int a, int b) : value{a+b} { print_created(this, a, b); } 121 Movable(const Movable &m) { value = m.value; print_copy_created(this); } 122 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); } 125private: 126 int value; 127}; 128 129class NCVirt { 130public: 131 virtual NonCopyable get_noncopyable(int a, int b) { return NonCopyable(a, b); } 132 virtual Movable get_movable(int a, int b) = 0; 133 134 std::string print_nc(int a, int b) { return get_noncopyable(a, b).get_value(); } 135 std::string print_movable(int a, int b) { return get_movable(a, b).get_value(); } 136}; 137class NCVirtTrampoline : public NCVirt { 138#if !defined(__INTEL_COMPILER) 139 NonCopyable get_noncopyable(int a, int b) override { 140 PYBIND11_OVERLOAD(NonCopyable, NCVirt, get_noncopyable, a, b); 141 } 142#endif 143 Movable get_movable(int a, int b) override { 144 PYBIND11_OVERLOAD_PURE(Movable, NCVirt, get_movable, a, b); 145 } 146}; 147 148int runExampleVirt(ExampleVirt *ex, int value) { 149 return ex->run(value); 150} 151 152bool runExampleVirtBool(ExampleVirt* ex) { 153 return ex->run_bool(); 154} 155 156void runExampleVirtVirtual(ExampleVirt *ex) { 157 ex->pure_virtual(); 158} 159 160 161// Inheriting virtual methods. We do two versions here: the repeat-everything version and the 162// templated trampoline versions mentioned in docs/advanced.rst. 163// 164// These base classes are exactly the same, but we technically need distinct 165// classes for this example code because we need to be able to bind them 166// properly (pybind11, sensibly, doesn't allow us to bind the same C++ class to 167// multiple python classes). 168class A_Repeat { 169#define A_METHODS \ 170public: \ 171 virtual int unlucky_number() = 0; \ 172 virtual std::string say_something(unsigned times) { \ 173 std::string s = ""; \ 174 for (unsigned i = 0; i < times; ++i) \ 175 s += "hi"; \ 176 return s; \ 177 } \ 178 std::string say_everything() { \ 179 return say_something(1) + " " + std::to_string(unlucky_number()); \ 180 } 181A_METHODS 182}; 183class B_Repeat : public A_Repeat { 184#define B_METHODS \ 185public: \ 186 int unlucky_number() override { return 13; } \ 187 std::string say_something(unsigned times) override { \ 188 return "B says hi " + std::to_string(times) + " times"; \ 189 } \ 190 virtual double lucky_number() { return 7.0; } 191B_METHODS 192}; 193class C_Repeat : public B_Repeat { 194#define C_METHODS \ 195public: \ 196 int unlucky_number() override { return 4444; } \ 197 double lucky_number() override { return 888; } 198C_METHODS 199}; 200class D_Repeat : public C_Repeat { 201#define D_METHODS // Nothing overridden. 202D_METHODS 203}; 204 205// Base classes for templated inheritance trampolines. Identical to the repeat-everything version: 206class A_Tpl { A_METHODS }; 207class B_Tpl : public A_Tpl { B_METHODS }; 208class C_Tpl : public B_Tpl { C_METHODS }; 209class D_Tpl : public C_Tpl { D_METHODS }; 210 211 212// Inheritance approach 1: each trampoline gets every virtual method (11 in total) 213class PyA_Repeat : public A_Repeat { 214public: 215 using A_Repeat::A_Repeat; 216 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}; 219class PyB_Repeat : public B_Repeat { 220public: 221 using B_Repeat::B_Repeat; 222 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 double lucky_number() override { PYBIND11_OVERLOAD(double, B_Repeat, lucky_number, ); } 225}; 226class PyC_Repeat : public C_Repeat { 227public: 228 using C_Repeat::C_Repeat; 229 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 double lucky_number() override { PYBIND11_OVERLOAD(double, C_Repeat, lucky_number, ); } 232}; 233class PyD_Repeat : public D_Repeat { 234public: 235 using D_Repeat::D_Repeat; 236 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 double lucky_number() override { PYBIND11_OVERLOAD(double, D_Repeat, lucky_number, ); } 239}; 240 241// Inheritance approach 2: templated trampoline classes. 242// 243// Advantages: 244// - we have only 2 (template) class and 4 method declarations (one per virtual method, plus one for 245// any override of a pure virtual method), versus 4 classes and 6 methods (MI) or 4 classes and 11 246// methods (repeat). 247// - Compared to MI, we also don't have to change the non-trampoline inheritance to virtual, and can 248// properly inherit constructors. 249// 250// Disadvantage: 251// - the compiler must still generate and compile 14 different methods (more, even, than the 11 252// required for the repeat approach) instead of the 6 required for MI. (If there was no pure 253// method (or no pure method override), the number would drop down to the same 11 as the repeat 254// approach). 255template <class Base = A_Tpl> 256class PyA_Tpl : public Base { 257public: 258 using Base::Base; // Inherit constructors 259 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}; 262template <class Base = B_Tpl> 263class PyB_Tpl : public PyA_Tpl<Base> { 264public: 265 using PyA_Tpl<Base>::PyA_Tpl; // Inherit constructors (via PyA_Tpl's inherited constructors) 266 int unlucky_number() override { PYBIND11_OVERLOAD(int, Base, unlucky_number, ); } 267 double lucky_number() override { PYBIND11_OVERLOAD(double, Base, lucky_number, ); } 268}; 269// Since C_Tpl and D_Tpl don't declare any new virtual methods, we don't actually need these (we can 270// use PyB_Tpl<C_Tpl> and PyB_Tpl<D_Tpl> for the trampoline classes instead): 271/* 272template <class Base = C_Tpl> class PyC_Tpl : public PyB_Tpl<Base> { 273public: 274 using PyB_Tpl<Base>::PyB_Tpl; 275}; 276template <class Base = D_Tpl> class PyD_Tpl : public PyC_Tpl<Base> { 277public: 278 using PyC_Tpl<Base>::PyC_Tpl; 279}; 280*/ 281 282 283void initialize_inherited_virtuals(py::module &m) { 284 // Method 1: repeat 285 py::class_<A_Repeat, PyA_Repeat>(m, "A_Repeat") 286 .def(py::init<>()) 287 .def("unlucky_number", &A_Repeat::unlucky_number) 288 .def("say_something", &A_Repeat::say_something) 289 .def("say_everything", &A_Repeat::say_everything); 290 py::class_<B_Repeat, A_Repeat, PyB_Repeat>(m, "B_Repeat") 291 .def(py::init<>()) 292 .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 .def(py::init<>()); 297 298 // Method 2: Templated trampolines 299 py::class_<A_Tpl, PyA_Tpl<>>(m, "A_Tpl") 300 .def(py::init<>()) 301 .def("unlucky_number", &A_Tpl::unlucky_number) 302 .def("say_something", &A_Tpl::say_something) 303 .def("say_everything", &A_Tpl::say_everything); 304 py::class_<B_Tpl, A_Tpl, PyB_Tpl<>>(m, "B_Tpl") 305 .def(py::init<>()) 306 .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 .def(py::init<>()); 311 312}; 313 314 315test_initializer virtual_functions([](py::module &m) { 316 /* Important: indicate the trampoline class PyExampleVirt using the third 317 argument to py::class_. The second argument with the unique pointer 318 is simply the default holder type used by pybind11. */ 319 py::class_<ExampleVirt, PyExampleVirt>(m, "ExampleVirt") 320 .def(py::init<int>()) 321 /* Reference original class in function definitions */ 322 .def("run", &ExampleVirt::run) 323 .def("run_bool", &ExampleVirt::run_bool) 324 .def("pure_virtual", &ExampleVirt::pure_virtual); 325 326 py::class_<NonCopyable>(m, "NonCopyable") 327 .def(py::init<int, int>()); 328 329 py::class_<Movable>(m, "Movable") 330 .def(py::init<int, int>()); 331 332#if !defined(__INTEL_COMPILER) 333 py::class_<NCVirt, NCVirtTrampoline>(m, "NCVirt") 334 .def(py::init<>()) 335 .def("get_noncopyable", &NCVirt::get_noncopyable) 336 .def("get_movable", &NCVirt::get_movable) 337 .def("print_nc", &NCVirt::print_nc) 338 .def("print_movable", &NCVirt::print_movable); 339#endif 340 341 m.def("runExampleVirt", &runExampleVirt); 342 m.def("runExampleVirtBool", &runExampleVirtBool); 343 m.def("runExampleVirtVirtual", &runExampleVirtVirtual); 344 345 m.def("cstats_debug", &ConstructorStats::get<ExampleVirt>); 346 initialize_inherited_virtuals(m); 347}); 348