test_virtual_functions.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. /*
  2. tests/test_virtual_functions.cpp -- overriding virtual functions from Python
  3. Copyright (c) 2016 Wenzel Jakob <[email protected]>
  4. All rights reserved. Use of this source code is governed by a
  5. BSD-style license that can be found in the LICENSE file.
  6. */
  7. #include "pybind11_tests.h"
  8. #include "constructor_stats.h"
  9. #include <pybind11/functional.h>
  10. #include <thread>
  11. /* This is an example class that we'll want to be able to extend from Python */
  12. class ExampleVirt {
  13. public:
  14. ExampleVirt(int state) : state(state) { print_created(this, state); }
  15. ExampleVirt(const ExampleVirt &e) : state(e.state) { print_copy_created(this); }
  16. ExampleVirt(ExampleVirt &&e) : state(e.state) { print_move_created(this); e.state = 0; }
  17. virtual ~ExampleVirt() { print_destroyed(this); }
  18. virtual int run(int value) {
  19. py::print("Original implementation of "
  20. "ExampleVirt::run(state={}, value={}, str1={}, str2={})"_s.format(state, value, get_string1(), *get_string2()));
  21. return state + value;
  22. }
  23. virtual bool run_bool() = 0;
  24. virtual void pure_virtual() = 0;
  25. // Returning a reference/pointer to a type converted from python (numbers, strings, etc.) is a
  26. // bit trickier, because the actual int& or std::string& or whatever only exists temporarily, so
  27. // we have to handle it specially in the trampoline class (see below).
  28. virtual const std::string &get_string1() { return str1; }
  29. virtual const std::string *get_string2() { return &str2; }
  30. private:
  31. int state;
  32. const std::string str1{"default1"}, str2{"default2"};
  33. };
  34. /* This is a wrapper class that must be generated */
  35. class PyExampleVirt : public ExampleVirt {
  36. public:
  37. using ExampleVirt::ExampleVirt; /* Inherit constructors */
  38. int run(int value) override {
  39. /* Generate wrapping code that enables native function overloading */
  40. PYBIND11_OVERLOAD(
  41. int, /* Return type */
  42. ExampleVirt, /* Parent class */
  43. run, /* Name of function */
  44. value /* Argument(s) */
  45. );
  46. }
  47. bool run_bool() override {
  48. PYBIND11_OVERLOAD_PURE(
  49. bool, /* Return type */
  50. ExampleVirt, /* Parent class */
  51. run_bool, /* Name of function */
  52. /* This function has no arguments. The trailing comma
  53. in the previous line is needed for some compilers */
  54. );
  55. }
  56. void pure_virtual() override {
  57. PYBIND11_OVERLOAD_PURE(
  58. void, /* Return type */
  59. ExampleVirt, /* Parent class */
  60. pure_virtual, /* Name of function */
  61. /* This function has no arguments. The trailing comma
  62. in the previous line is needed for some compilers */
  63. );
  64. }
  65. // We can return reference types for compatibility with C++ virtual interfaces that do so, but
  66. // note they have some significant limitations (see the documentation).
  67. const std::string &get_string1() override {
  68. PYBIND11_OVERLOAD(
  69. const std::string &, /* Return type */
  70. ExampleVirt, /* Parent class */
  71. get_string1, /* Name of function */
  72. /* (no arguments) */
  73. );
  74. }
  75. const std::string *get_string2() override {
  76. PYBIND11_OVERLOAD(
  77. const std::string *, /* Return type */
  78. ExampleVirt, /* Parent class */
  79. get_string2, /* Name of function */
  80. /* (no arguments) */
  81. );
  82. }
  83. };
  84. class NonCopyable {
  85. public:
  86. NonCopyable(int a, int b) : value{new int(a*b)} { print_created(this, a, b); }
  87. NonCopyable(NonCopyable &&o) { value = std::move(o.value); print_move_created(this); }
  88. NonCopyable(const NonCopyable &) = delete;
  89. NonCopyable() = delete;
  90. void operator=(const NonCopyable &) = delete;
  91. void operator=(NonCopyable &&) = delete;
  92. std::string get_value() const {
  93. if (value) return std::to_string(*value); else return "(null)";
  94. }
  95. ~NonCopyable() { print_destroyed(this); }
  96. private:
  97. std::unique_ptr<int> value;
  98. };
  99. // This is like the above, but is both copy and movable. In effect this means it should get moved
  100. // when it is not referenced elsewhere, but copied if it is still referenced.
  101. class Movable {
  102. public:
  103. Movable(int a, int b) : value{a+b} { print_created(this, a, b); }
  104. Movable(const Movable &m) { value = m.value; print_copy_created(this); }
  105. Movable(Movable &&m) { value = std::move(m.value); print_move_created(this); }
  106. std::string get_value() const { return std::to_string(value); }
  107. ~Movable() { print_destroyed(this); }
  108. private:
  109. int value;
  110. };
  111. class NCVirt {
  112. public:
  113. virtual NonCopyable get_noncopyable(int a, int b) { return NonCopyable(a, b); }
  114. virtual Movable get_movable(int a, int b) = 0;
  115. std::string print_nc(int a, int b) { return get_noncopyable(a, b).get_value(); }
  116. std::string print_movable(int a, int b) { return get_movable(a, b).get_value(); }
  117. };
  118. class NCVirtTrampoline : public NCVirt {
  119. #if !defined(__INTEL_COMPILER)
  120. NonCopyable get_noncopyable(int a, int b) override {
  121. PYBIND11_OVERLOAD(NonCopyable, NCVirt, get_noncopyable, a, b);
  122. }
  123. #endif
  124. Movable get_movable(int a, int b) override {
  125. PYBIND11_OVERLOAD_PURE(Movable, NCVirt, get_movable, a, b);
  126. }
  127. };
  128. struct Base {
  129. /* for some reason MSVC2015 can't compile this if the function is pure virtual */
  130. virtual std::string dispatch() const { return {}; };
  131. virtual ~Base() = default;
  132. };
  133. struct DispatchIssue : Base {
  134. virtual std::string dispatch() const {
  135. PYBIND11_OVERLOAD_PURE(std::string, Base, dispatch, /* no arguments */);
  136. }
  137. };
  138. static void test_gil() {
  139. {
  140. py::gil_scoped_acquire lock;
  141. py::print("1st lock acquired");
  142. }
  143. {
  144. py::gil_scoped_acquire lock;
  145. py::print("2nd lock acquired");
  146. }
  147. }
  148. static void test_gil_from_thread() {
  149. py::gil_scoped_release release;
  150. std::thread t(test_gil);
  151. t.join();
  152. }
  153. // Forward declaration (so that we can put the main tests here; the inherited virtual approaches are
  154. // rather long).
  155. void initialize_inherited_virtuals(py::module &m);
  156. TEST_SUBMODULE(virtual_functions, m) {
  157. // test_override
  158. py::class_<ExampleVirt, PyExampleVirt>(m, "ExampleVirt")
  159. .def(py::init<int>())
  160. /* Reference original class in function definitions */
  161. .def("run", &ExampleVirt::run)
  162. .def("run_bool", &ExampleVirt::run_bool)
  163. .def("pure_virtual", &ExampleVirt::pure_virtual);
  164. py::class_<NonCopyable>(m, "NonCopyable")
  165. .def(py::init<int, int>());
  166. py::class_<Movable>(m, "Movable")
  167. .def(py::init<int, int>());
  168. // test_move_support
  169. #if !defined(__INTEL_COMPILER)
  170. py::class_<NCVirt, NCVirtTrampoline>(m, "NCVirt")
  171. .def(py::init<>())
  172. .def("get_noncopyable", &NCVirt::get_noncopyable)
  173. .def("get_movable", &NCVirt::get_movable)
  174. .def("print_nc", &NCVirt::print_nc)
  175. .def("print_movable", &NCVirt::print_movable);
  176. #endif
  177. m.def("runExampleVirt", [](ExampleVirt *ex, int value) { return ex->run(value); });
  178. m.def("runExampleVirtBool", [](ExampleVirt* ex) { return ex->run_bool(); });
  179. m.def("runExampleVirtVirtual", [](ExampleVirt *ex) { ex->pure_virtual(); });
  180. m.def("cstats_debug", &ConstructorStats::get<ExampleVirt>);
  181. initialize_inherited_virtuals(m);
  182. // test_alias_delay_initialization1
  183. // don't invoke Python dispatch classes by default when instantiating C++ classes
  184. // that were not extended on the Python side
  185. struct A {
  186. virtual ~A() {}
  187. virtual void f() { py::print("A.f()"); }
  188. };
  189. struct PyA : A {
  190. PyA() { py::print("PyA.PyA()"); }
  191. ~PyA() { py::print("PyA.~PyA()"); }
  192. void f() override {
  193. py::print("PyA.f()");
  194. PYBIND11_OVERLOAD(void, A, f);
  195. }
  196. };
  197. py::class_<A, PyA>(m, "A")
  198. .def(py::init<>())
  199. .def("f", &A::f);
  200. m.def("call_f", [](A *a) { a->f(); });
  201. // test_alias_delay_initialization2
  202. // ... unless we explicitly request it, as in this example:
  203. struct A2 {
  204. virtual ~A2() {}
  205. virtual void f() { py::print("A2.f()"); }
  206. };
  207. struct PyA2 : A2 {
  208. PyA2() { py::print("PyA2.PyA2()"); }
  209. ~PyA2() { py::print("PyA2.~PyA2()"); }
  210. void f() override {
  211. py::print("PyA2.f()");
  212. PYBIND11_OVERLOAD(void, A2, f);
  213. }
  214. };
  215. py::class_<A2, PyA2>(m, "A2")
  216. .def(py::init_alias<>())
  217. .def(py::init([](int) { return new PyA2(); }))
  218. .def("f", &A2::f);
  219. m.def("call_f", [](A2 *a2) { a2->f(); });
  220. // test_dispatch_issue
  221. // #159: virtual function dispatch has problems with similar-named functions
  222. py::class_<Base, DispatchIssue>(m, "DispatchIssue")
  223. .def(py::init<>())
  224. .def("dispatch", &Base::dispatch);
  225. m.def("dispatch_issue_go", [](const Base * b) { return b->dispatch(); });
  226. // test_override_ref
  227. // #392/397: overriding reference-returning functions
  228. class OverrideTest {
  229. public:
  230. struct A { std::string value = "hi"; };
  231. std::string v;
  232. A a;
  233. explicit OverrideTest(const std::string &v) : v{v} {}
  234. virtual std::string str_value() { return v; }
  235. virtual std::string &str_ref() { return v; }
  236. virtual A A_value() { return a; }
  237. virtual A &A_ref() { return a; }
  238. virtual ~OverrideTest() = default;
  239. };
  240. class PyOverrideTest : public OverrideTest {
  241. public:
  242. using OverrideTest::OverrideTest;
  243. std::string str_value() override { PYBIND11_OVERLOAD(std::string, OverrideTest, str_value); }
  244. // Not allowed (uncommenting should hit a static_assert failure): we can't get a reference
  245. // to a python numeric value, since we only copy values in the numeric type caster:
  246. // std::string &str_ref() override { PYBIND11_OVERLOAD(std::string &, OverrideTest, str_ref); }
  247. // But we can work around it like this:
  248. private:
  249. std::string _tmp;
  250. std::string str_ref_helper() { PYBIND11_OVERLOAD(std::string, OverrideTest, str_ref); }
  251. public:
  252. std::string &str_ref() override { return _tmp = str_ref_helper(); }
  253. A A_value() override { PYBIND11_OVERLOAD(A, OverrideTest, A_value); }
  254. A &A_ref() override { PYBIND11_OVERLOAD(A &, OverrideTest, A_ref); }
  255. };
  256. py::class_<OverrideTest::A>(m, "OverrideTest_A")
  257. .def_readwrite("value", &OverrideTest::A::value);
  258. py::class_<OverrideTest, PyOverrideTest>(m, "OverrideTest")
  259. .def(py::init<const std::string &>())
  260. .def("str_value", &OverrideTest::str_value)
  261. // .def("str_ref", &OverrideTest::str_ref)
  262. .def("A_value", &OverrideTest::A_value)
  263. .def("A_ref", &OverrideTest::A_ref);
  264. }
  265. // Inheriting virtual methods. We do two versions here: the repeat-everything version and the
  266. // templated trampoline versions mentioned in docs/advanced.rst.
  267. //
  268. // These base classes are exactly the same, but we technically need distinct
  269. // classes for this example code because we need to be able to bind them
  270. // properly (pybind11, sensibly, doesn't allow us to bind the same C++ class to
  271. // multiple python classes).
  272. class A_Repeat {
  273. #define A_METHODS \
  274. public: \
  275. virtual int unlucky_number() = 0; \
  276. virtual std::string say_something(unsigned times) { \
  277. std::string s = ""; \
  278. for (unsigned i = 0; i < times; ++i) \
  279. s += "hi"; \
  280. return s; \
  281. } \
  282. std::string say_everything() { \
  283. return say_something(1) + " " + std::to_string(unlucky_number()); \
  284. }
  285. A_METHODS
  286. virtual ~A_Repeat() = default;
  287. };
  288. class B_Repeat : public A_Repeat {
  289. #define B_METHODS \
  290. public: \
  291. int unlucky_number() override { return 13; } \
  292. std::string say_something(unsigned times) override { \
  293. return "B says hi " + std::to_string(times) + " times"; \
  294. } \
  295. virtual double lucky_number() { return 7.0; }
  296. B_METHODS
  297. };
  298. class C_Repeat : public B_Repeat {
  299. #define C_METHODS \
  300. public: \
  301. int unlucky_number() override { return 4444; } \
  302. double lucky_number() override { return 888; }
  303. C_METHODS
  304. };
  305. class D_Repeat : public C_Repeat {
  306. #define D_METHODS // Nothing overridden.
  307. D_METHODS
  308. };
  309. // Base classes for templated inheritance trampolines. Identical to the repeat-everything version:
  310. class A_Tpl { A_METHODS; virtual ~A_Tpl() = default; };
  311. class B_Tpl : public A_Tpl { B_METHODS };
  312. class C_Tpl : public B_Tpl { C_METHODS };
  313. class D_Tpl : public C_Tpl { D_METHODS };
  314. // Inheritance approach 1: each trampoline gets every virtual method (11 in total)
  315. class PyA_Repeat : public A_Repeat {
  316. public:
  317. using A_Repeat::A_Repeat;
  318. int unlucky_number() override { PYBIND11_OVERLOAD_PURE(int, A_Repeat, unlucky_number, ); }
  319. std::string say_something(unsigned times) override { PYBIND11_OVERLOAD(std::string, A_Repeat, say_something, times); }
  320. };
  321. class PyB_Repeat : public B_Repeat {
  322. public:
  323. using B_Repeat::B_Repeat;
  324. int unlucky_number() override { PYBIND11_OVERLOAD(int, B_Repeat, unlucky_number, ); }
  325. std::string say_something(unsigned times) override { PYBIND11_OVERLOAD(std::string, B_Repeat, say_something, times); }
  326. double lucky_number() override { PYBIND11_OVERLOAD(double, B_Repeat, lucky_number, ); }
  327. };
  328. class PyC_Repeat : public C_Repeat {
  329. public:
  330. using C_Repeat::C_Repeat;
  331. int unlucky_number() override { PYBIND11_OVERLOAD(int, C_Repeat, unlucky_number, ); }
  332. std::string say_something(unsigned times) override { PYBIND11_OVERLOAD(std::string, C_Repeat, say_something, times); }
  333. double lucky_number() override { PYBIND11_OVERLOAD(double, C_Repeat, lucky_number, ); }
  334. };
  335. class PyD_Repeat : public D_Repeat {
  336. public:
  337. using D_Repeat::D_Repeat;
  338. int unlucky_number() override { PYBIND11_OVERLOAD(int, D_Repeat, unlucky_number, ); }
  339. std::string say_something(unsigned times) override { PYBIND11_OVERLOAD(std::string, D_Repeat, say_something, times); }
  340. double lucky_number() override { PYBIND11_OVERLOAD(double, D_Repeat, lucky_number, ); }
  341. };
  342. // Inheritance approach 2: templated trampoline classes.
  343. //
  344. // Advantages:
  345. // - we have only 2 (template) class and 4 method declarations (one per virtual method, plus one for
  346. // any override of a pure virtual method), versus 4 classes and 6 methods (MI) or 4 classes and 11
  347. // methods (repeat).
  348. // - Compared to MI, we also don't have to change the non-trampoline inheritance to virtual, and can
  349. // properly inherit constructors.
  350. //
  351. // Disadvantage:
  352. // - the compiler must still generate and compile 14 different methods (more, even, than the 11
  353. // required for the repeat approach) instead of the 6 required for MI. (If there was no pure
  354. // method (or no pure method override), the number would drop down to the same 11 as the repeat
  355. // approach).
  356. template <class Base = A_Tpl>
  357. class PyA_Tpl : public Base {
  358. public:
  359. using Base::Base; // Inherit constructors
  360. int unlucky_number() override { PYBIND11_OVERLOAD_PURE(int, Base, unlucky_number, ); }
  361. std::string say_something(unsigned times) override { PYBIND11_OVERLOAD(std::string, Base, say_something, times); }
  362. };
  363. template <class Base = B_Tpl>
  364. class PyB_Tpl : public PyA_Tpl<Base> {
  365. public:
  366. using PyA_Tpl<Base>::PyA_Tpl; // Inherit constructors (via PyA_Tpl's inherited constructors)
  367. int unlucky_number() override { PYBIND11_OVERLOAD(int, Base, unlucky_number, ); }
  368. double lucky_number() override { PYBIND11_OVERLOAD(double, Base, lucky_number, ); }
  369. };
  370. // Since C_Tpl and D_Tpl don't declare any new virtual methods, we don't actually need these (we can
  371. // use PyB_Tpl<C_Tpl> and PyB_Tpl<D_Tpl> for the trampoline classes instead):
  372. /*
  373. template <class Base = C_Tpl> class PyC_Tpl : public PyB_Tpl<Base> {
  374. public:
  375. using PyB_Tpl<Base>::PyB_Tpl;
  376. };
  377. template <class Base = D_Tpl> class PyD_Tpl : public PyC_Tpl<Base> {
  378. public:
  379. using PyC_Tpl<Base>::PyC_Tpl;
  380. };
  381. */
  382. void initialize_inherited_virtuals(py::module &m) {
  383. // test_inherited_virtuals
  384. // Method 1: repeat
  385. py::class_<A_Repeat, PyA_Repeat>(m, "A_Repeat")
  386. .def(py::init<>())
  387. .def("unlucky_number", &A_Repeat::unlucky_number)
  388. .def("say_something", &A_Repeat::say_something)
  389. .def("say_everything", &A_Repeat::say_everything);
  390. py::class_<B_Repeat, A_Repeat, PyB_Repeat>(m, "B_Repeat")
  391. .def(py::init<>())
  392. .def("lucky_number", &B_Repeat::lucky_number);
  393. py::class_<C_Repeat, B_Repeat, PyC_Repeat>(m, "C_Repeat")
  394. .def(py::init<>());
  395. py::class_<D_Repeat, C_Repeat, PyD_Repeat>(m, "D_Repeat")
  396. .def(py::init<>());
  397. // test_
  398. // Method 2: Templated trampolines
  399. py::class_<A_Tpl, PyA_Tpl<>>(m, "A_Tpl")
  400. .def(py::init<>())
  401. .def("unlucky_number", &A_Tpl::unlucky_number)
  402. .def("say_something", &A_Tpl::say_something)
  403. .def("say_everything", &A_Tpl::say_everything);
  404. py::class_<B_Tpl, A_Tpl, PyB_Tpl<>>(m, "B_Tpl")
  405. .def(py::init<>())
  406. .def("lucky_number", &B_Tpl::lucky_number);
  407. py::class_<C_Tpl, B_Tpl, PyB_Tpl<C_Tpl>>(m, "C_Tpl")
  408. .def(py::init<>());
  409. py::class_<D_Tpl, C_Tpl, PyB_Tpl<D_Tpl>>(m, "D_Tpl")
  410. .def(py::init<>());
  411. // Fix issue #1454 (crash when acquiring/releasing GIL on another thread in Python 2.7)
  412. m.def("test_gil", &test_gil);
  413. m.def("test_gil_from_thread", &test_gil_from_thread);
  414. };