You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

98 lines
2.8 KiB

  1. /*
  2. example/example12.cpp -- overriding virtual functions from Python
  3. Copyright (c) 2015 Wenzel Jakob <wenzel@inf.ethz.ch>
  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 "example.h"
  8. #include <pybind11/functional.h>
  9. /* This is an example class that we'll want to be able to extend from Python */
  10. class Example12 {
  11. public:
  12. Example12(int state) : state(state) {
  13. cout << "Constructing Example12.." << endl;
  14. }
  15. ~Example12() {
  16. cout << "Destructing Example12.." << endl;
  17. }
  18. virtual int run(int value) {
  19. std::cout << "Original implementation of Example12::run(state=" << state
  20. << ", value=" << value << ")" << std::endl;
  21. return state + value;
  22. }
  23. virtual bool run_bool() = 0;
  24. virtual void pure_virtual() = 0;
  25. private:
  26. int state;
  27. };
  28. /* This is a wrapper class that must be generated */
  29. class PyExample12 : public Example12 {
  30. public:
  31. using Example12::Example12; /* Inherit constructors */
  32. virtual int run(int value) {
  33. /* Generate wrapping code that enables native function overloading */
  34. PYBIND11_OVERLOAD(
  35. int, /* Return type */
  36. Example12, /* Parent class */
  37. run, /* Name of function */
  38. value /* Argument(s) */
  39. );
  40. }
  41. virtual bool run_bool() {
  42. PYBIND11_OVERLOAD_PURE(
  43. bool,
  44. Example12,
  45. run_bool
  46. );
  47. throw std::runtime_error("this will never be reached");
  48. }
  49. virtual void pure_virtual() {
  50. PYBIND11_OVERLOAD_PURE(
  51. void, /* Return type */
  52. Example12, /* Parent class */
  53. pure_virtual /* Name of function */
  54. /* This function has no arguments */
  55. );
  56. }
  57. };
  58. int runExample12(Example12 *ex, int value) {
  59. return ex->run(value);
  60. }
  61. bool runExample12Bool(Example12* ex) {
  62. return ex->run_bool();
  63. }
  64. void runExample12Virtual(Example12 *ex) {
  65. ex->pure_virtual();
  66. }
  67. void init_ex12(py::module &m) {
  68. /* Important: use the wrapper type as a template
  69. argument to class_<>, but use the original name
  70. to denote the type */
  71. py::class_<PyExample12>(m, "Example12")
  72. /* Declare that 'PyExample12' is really an alias for the original type 'Example12' */
  73. .alias<Example12>()
  74. .def(py::init<int>())
  75. /* Reference original class in function definitions */
  76. .def("run", &Example12::run)
  77. .def("run_bool", &Example12::run_bool)
  78. .def("pure_virtual", &Example12::pure_virtual);
  79. m.def("runExample12", &runExample12);
  80. m.def("runExample12Bool", &runExample12Bool);
  81. m.def("runExample12Virtual", &runExample12Virtual);
  82. }