Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 1 | Classes |
| 2 | ####### |
| 3 | |
| 4 | This section presents advanced binding code for classes and it is assumed |
| 5 | that you are already familiar with the basics from :doc:`/classes`. |
| 6 | |
| 7 | .. _overriding_virtuals: |
| 8 | |
| 9 | Overriding virtual functions in Python |
| 10 | ====================================== |
| 11 | |
| 12 | Suppose that a C++ class or interface has a virtual function that we'd like to |
| 13 | to override from within Python (we'll focus on the class ``Animal``; ``Dog`` is |
| 14 | given as a specific example of how one would do this with traditional C++ |
| 15 | code). |
| 16 | |
| 17 | .. code-block:: cpp |
| 18 | |
| 19 | class Animal { |
| 20 | public: |
| 21 | virtual ~Animal() { } |
| 22 | virtual std::string go(int n_times) = 0; |
| 23 | }; |
| 24 | |
| 25 | class Dog : public Animal { |
| 26 | public: |
| 27 | std::string go(int n_times) override { |
| 28 | std::string result; |
| 29 | for (int i=0; i<n_times; ++i) |
| 30 | result += "woof! "; |
| 31 | return result; |
| 32 | } |
| 33 | }; |
| 34 | |
| 35 | Let's also suppose that we are given a plain function which calls the |
| 36 | function ``go()`` on an arbitrary ``Animal`` instance. |
| 37 | |
| 38 | .. code-block:: cpp |
| 39 | |
| 40 | std::string call_go(Animal *animal) { |
| 41 | return animal->go(3); |
| 42 | } |
| 43 | |
| 44 | Normally, the binding code for these classes would look as follows: |
| 45 | |
| 46 | .. code-block:: cpp |
| 47 | |
Dean Moldovan | 443ab59 | 2017-04-24 01:51:44 +0200 | [diff] [blame] | 48 | PYBIND11_MODULE(example, m) { |
François Becker | ce9d6e2 | 2018-05-07 15:18:08 +0200 | [diff] [blame] | 49 | py::class_<Animal>(m, "Animal") |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 50 | .def("go", &Animal::go); |
| 51 | |
Tom de Geus | a7ff616 | 2018-05-04 17:04:45 +0200 | [diff] [blame] | 52 | py::class_<Dog, Animal>(m, "Dog") |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 53 | .def(py::init<>()); |
| 54 | |
| 55 | m.def("call_go", &call_go); |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 56 | } |
| 57 | |
| 58 | However, these bindings are impossible to extend: ``Animal`` is not |
| 59 | constructible, and we clearly require some kind of "trampoline" that |
| 60 | redirects virtual calls back to Python. |
| 61 | |
| 62 | Defining a new type of ``Animal`` from within Python is possible but requires a |
| 63 | helper class that is defined as follows: |
| 64 | |
| 65 | .. code-block:: cpp |
| 66 | |
| 67 | class PyAnimal : public Animal { |
| 68 | public: |
| 69 | /* Inherit the constructors */ |
| 70 | using Animal::Animal; |
| 71 | |
| 72 | /* Trampoline (need one for each virtual function) */ |
| 73 | std::string go(int n_times) override { |
Yannick Jadoul | d65e34d | 2020-09-15 14:56:20 +0200 | [diff] [blame] | 74 | PYBIND11_OVERRIDE_PURE( |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 75 | std::string, /* Return type */ |
| 76 | Animal, /* Parent class */ |
jbarlow83 | 7830e85 | 2017-01-13 02:17:29 -0800 | [diff] [blame] | 77 | go, /* Name of function in C++ (must match Python name) */ |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 78 | n_times /* Argument(s) */ |
| 79 | ); |
| 80 | } |
| 81 | }; |
| 82 | |
Yannick Jadoul | d65e34d | 2020-09-15 14:56:20 +0200 | [diff] [blame] | 83 | The macro :c:macro:`PYBIND11_OVERRIDE_PURE` should be used for pure virtual |
| 84 | functions, and :c:macro:`PYBIND11_OVERRIDE` should be used for functions which have |
Henry Schreiner | d8c7ee0 | 2020-07-20 13:35:21 -0400 | [diff] [blame] | 85 | a default implementation. There are also two alternate macros |
Yannick Jadoul | d65e34d | 2020-09-15 14:56:20 +0200 | [diff] [blame] | 86 | :c:macro:`PYBIND11_OVERRIDE_PURE_NAME` and :c:macro:`PYBIND11_OVERRIDE_NAME` which |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 87 | take a string-valued name argument between the *Parent class* and *Name of the |
Dean Moldovan | 234f7c3 | 2017-08-17 17:03:46 +0200 | [diff] [blame] | 88 | function* slots, which defines the name of function in Python. This is required |
jbarlow83 | 7830e85 | 2017-01-13 02:17:29 -0800 | [diff] [blame] | 89 | when the C++ and Python versions of the |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 90 | function have different names, e.g. ``operator()`` vs ``__call__``. |
| 91 | |
| 92 | The binding code also needs a few minor adaptations (highlighted): |
| 93 | |
| 94 | .. code-block:: cpp |
Tom de Geus | a7ff616 | 2018-05-04 17:04:45 +0200 | [diff] [blame] | 95 | :emphasize-lines: 2,3 |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 96 | |
Dean Moldovan | 443ab59 | 2017-04-24 01:51:44 +0200 | [diff] [blame] | 97 | PYBIND11_MODULE(example, m) { |
François Becker | ce9d6e2 | 2018-05-07 15:18:08 +0200 | [diff] [blame] | 98 | py::class_<Animal, PyAnimal /* <--- trampoline*/>(m, "Animal") |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 99 | .def(py::init<>()) |
| 100 | .def("go", &Animal::go); |
| 101 | |
Tom de Geus | a7ff616 | 2018-05-04 17:04:45 +0200 | [diff] [blame] | 102 | py::class_<Dog, Animal>(m, "Dog") |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 103 | .def(py::init<>()); |
| 104 | |
| 105 | m.def("call_go", &call_go); |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 106 | } |
| 107 | |
| 108 | Importantly, pybind11 is made aware of the trampoline helper class by |
jbarlow83 | 7830e85 | 2017-01-13 02:17:29 -0800 | [diff] [blame] | 109 | specifying it as an extra template argument to :class:`class_`. (This can also |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 110 | be combined with other template arguments such as a custom holder type; the |
| 111 | order of template types does not matter). Following this, we are able to |
| 112 | define a constructor as usual. |
| 113 | |
jbarlow83 | 7830e85 | 2017-01-13 02:17:29 -0800 | [diff] [blame] | 114 | Bindings should be made against the actual class, not the trampoline helper class. |
| 115 | |
| 116 | .. code-block:: cpp |
Tom de Geus | a7ff616 | 2018-05-04 17:04:45 +0200 | [diff] [blame] | 117 | :emphasize-lines: 3 |
jbarlow83 | 7830e85 | 2017-01-13 02:17:29 -0800 | [diff] [blame] | 118 | |
Tom de Geus | a7ff616 | 2018-05-04 17:04:45 +0200 | [diff] [blame] | 119 | py::class_<Animal, PyAnimal /* <--- trampoline*/>(m, "Animal"); |
| 120 | .def(py::init<>()) |
| 121 | .def("go", &PyAnimal::go); /* <--- THIS IS WRONG, use &Animal::go */ |
jbarlow83 | 7830e85 | 2017-01-13 02:17:29 -0800 | [diff] [blame] | 122 | |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 123 | Note, however, that the above is sufficient for allowing python classes to |
EricCousineau-TRI | e06077b | 2017-08-07 18:37:42 -0400 | [diff] [blame] | 124 | extend ``Animal``, but not ``Dog``: see :ref:`virtual_and_inheritance` for the |
Yannick Jadoul | d65e34d | 2020-09-15 14:56:20 +0200 | [diff] [blame] | 125 | necessary steps required to providing proper overriding support for inherited |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 126 | classes. |
| 127 | |
| 128 | The Python session below shows how to override ``Animal::go`` and invoke it via |
| 129 | a virtual method call. |
| 130 | |
| 131 | .. code-block:: pycon |
| 132 | |
| 133 | >>> from example import * |
| 134 | >>> d = Dog() |
| 135 | >>> call_go(d) |
| 136 | u'woof! woof! woof! ' |
| 137 | >>> class Cat(Animal): |
| 138 | ... def go(self, n_times): |
| 139 | ... return "meow! " * n_times |
| 140 | ... |
| 141 | >>> c = Cat() |
| 142 | >>> call_go(c) |
| 143 | u'meow! meow! meow! ' |
| 144 | |
EricCousineau-TRI | e06077b | 2017-08-07 18:37:42 -0400 | [diff] [blame] | 145 | If you are defining a custom constructor in a derived Python class, you *must* |
| 146 | ensure that you explicitly call the bound C++ constructor using ``__init__``, |
| 147 | *regardless* of whether it is a default constructor or not. Otherwise, the |
| 148 | memory for the C++ portion of the instance will be left uninitialized, which |
| 149 | will generally leave the C++ instance in an invalid state and cause undefined |
| 150 | behavior if the C++ instance is subsequently used. |
| 151 | |
Henry Schreiner | a6887b6 | 2020-08-19 14:53:59 -0400 | [diff] [blame] | 152 | .. versionchanged:: 2.6 |
Dustin Spicuzza | 1b0bf35 | 2020-07-07 06:04:06 -0400 | [diff] [blame] | 153 | The default pybind11 metaclass will throw a ``TypeError`` when it detects |
| 154 | that ``__init__`` was not called by a derived class. |
| 155 | |
EricCousineau-TRI | e06077b | 2017-08-07 18:37:42 -0400 | [diff] [blame] | 156 | Here is an example: |
| 157 | |
| 158 | .. code-block:: python |
| 159 | |
Manuel Schneider | 492da59 | 2019-06-10 22:02:58 +0200 | [diff] [blame] | 160 | class Dachshund(Dog): |
EricCousineau-TRI | e06077b | 2017-08-07 18:37:42 -0400 | [diff] [blame] | 161 | def __init__(self, name): |
Yannick Jadoul | b3d8fec | 2020-08-24 00:00:12 +0200 | [diff] [blame] | 162 | Dog.__init__(self) # Without this, a TypeError is raised. |
EricCousineau-TRI | e06077b | 2017-08-07 18:37:42 -0400 | [diff] [blame] | 163 | self.name = name |
| 164 | def bark(self): |
| 165 | return "yap!" |
| 166 | |
| 167 | Note that a direct ``__init__`` constructor *should be called*, and ``super()`` |
| 168 | should not be used. For simple cases of linear inheritance, ``super()`` |
| 169 | may work, but once you begin mixing Python and C++ multiple inheritance, |
| 170 | things will fall apart due to differences between Python's MRO and C++'s |
| 171 | mechanisms. |
| 172 | |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 173 | Please take a look at the :ref:`macro_notes` before using this feature. |
| 174 | |
| 175 | .. note:: |
| 176 | |
| 177 | When the overridden type returns a reference or pointer to a type that |
| 178 | pybind11 converts from Python (for example, numeric values, std::string, |
| 179 | and other built-in value-converting types), there are some limitations to |
| 180 | be aware of: |
| 181 | |
| 182 | - because in these cases there is no C++ variable to reference (the value |
| 183 | is stored in the referenced Python variable), pybind11 provides one in |
Yannick Jadoul | d65e34d | 2020-09-15 14:56:20 +0200 | [diff] [blame] | 184 | the PYBIND11_OVERRIDE macros (when needed) with static storage duration. |
| 185 | Note that this means that invoking the overridden method on *any* |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 186 | instance will change the referenced value stored in *all* instances of |
| 187 | that type. |
| 188 | |
| 189 | - Attempts to modify a non-const reference will not have the desired |
| 190 | effect: it will change only the static cache variable, but this change |
| 191 | will not propagate to underlying Python instance, and the change will be |
Yannick Jadoul | d65e34d | 2020-09-15 14:56:20 +0200 | [diff] [blame] | 192 | replaced the next time the override is invoked. |
| 193 | |
| 194 | .. warning:: |
| 195 | |
| 196 | The :c:macro:`PYBIND11_OVERRIDE` and accompanying macros used to be called |
| 197 | ``PYBIND11_OVERLOAD`` up until pybind11 v2.5.0, and :func:`get_override` |
| 198 | used to be called ``get_overload``. This naming was corrected and the older |
Henry Schreiner | dabbbf3 | 2020-09-15 12:10:31 -0400 | [diff] [blame] | 199 | macro and function names may soon be deprecated, in order to reduce |
| 200 | confusion with overloaded functions and methods and ``py::overload_cast`` |
| 201 | (see :ref:`classes`). |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 202 | |
| 203 | .. seealso:: |
| 204 | |
| 205 | The file :file:`tests/test_virtual_functions.cpp` contains a complete |
| 206 | example that demonstrates how to override virtual functions using pybind11 |
| 207 | in more detail. |
| 208 | |
| 209 | .. _virtual_and_inheritance: |
| 210 | |
| 211 | Combining virtual functions and inheritance |
| 212 | =========================================== |
| 213 | |
| 214 | When combining virtual methods with inheritance, you need to be sure to provide |
| 215 | an override for each method for which you want to allow overrides from derived |
| 216 | python classes. For example, suppose we extend the above ``Animal``/``Dog`` |
| 217 | example as follows: |
| 218 | |
| 219 | .. code-block:: cpp |
| 220 | |
| 221 | class Animal { |
| 222 | public: |
| 223 | virtual std::string go(int n_times) = 0; |
| 224 | virtual std::string name() { return "unknown"; } |
| 225 | }; |
myd7349 | 9b815ad | 2017-01-13 18:15:52 +0800 | [diff] [blame] | 226 | class Dog : public Animal { |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 227 | public: |
| 228 | std::string go(int n_times) override { |
| 229 | std::string result; |
| 230 | for (int i=0; i<n_times; ++i) |
| 231 | result += bark() + " "; |
| 232 | return result; |
| 233 | } |
| 234 | virtual std::string bark() { return "woof!"; } |
| 235 | }; |
| 236 | |
| 237 | then the trampoline class for ``Animal`` must, as described in the previous |
| 238 | section, override ``go()`` and ``name()``, but in order to allow python code to |
| 239 | inherit properly from ``Dog``, we also need a trampoline class for ``Dog`` that |
| 240 | overrides both the added ``bark()`` method *and* the ``go()`` and ``name()`` |
| 241 | methods inherited from ``Animal`` (even though ``Dog`` doesn't directly |
| 242 | override the ``name()`` method): |
| 243 | |
| 244 | .. code-block:: cpp |
| 245 | |
| 246 | class PyAnimal : public Animal { |
| 247 | public: |
| 248 | using Animal::Animal; // Inherit constructors |
Yannick Jadoul | d65e34d | 2020-09-15 14:56:20 +0200 | [diff] [blame] | 249 | std::string go(int n_times) override { PYBIND11_OVERRIDE_PURE(std::string, Animal, go, n_times); } |
| 250 | std::string name() override { PYBIND11_OVERRIDE(std::string, Animal, name, ); } |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 251 | }; |
| 252 | class PyDog : public Dog { |
| 253 | public: |
| 254 | using Dog::Dog; // Inherit constructors |
Yannick Jadoul | d65e34d | 2020-09-15 14:56:20 +0200 | [diff] [blame] | 255 | std::string go(int n_times) override { PYBIND11_OVERRIDE(std::string, Dog, go, n_times); } |
| 256 | std::string name() override { PYBIND11_OVERRIDE(std::string, Dog, name, ); } |
| 257 | std::string bark() override { PYBIND11_OVERRIDE(std::string, Dog, bark, ); } |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 258 | }; |
| 259 | |
Wenzel Jakob | ab26259 | 2017-03-22 21:39:19 +0100 | [diff] [blame] | 260 | .. note:: |
| 261 | |
Yannick Jadoul | d65e34d | 2020-09-15 14:56:20 +0200 | [diff] [blame] | 262 | Note the trailing commas in the ``PYBIND11_OVERIDE`` calls to ``name()`` |
Wenzel Jakob | ab26259 | 2017-03-22 21:39:19 +0100 | [diff] [blame] | 263 | and ``bark()``. These are needed to portably implement a trampoline for a |
| 264 | function that does not take any arguments. For functions that take |
| 265 | a nonzero number of arguments, the trailing comma must be omitted. |
| 266 | |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 267 | A registered class derived from a pybind11-registered class with virtual |
| 268 | methods requires a similar trampoline class, *even if* it doesn't explicitly |
| 269 | declare or override any virtual methods itself: |
| 270 | |
| 271 | .. code-block:: cpp |
| 272 | |
| 273 | class Husky : public Dog {}; |
| 274 | class PyHusky : public Husky { |
myd7349 | 9b815ad | 2017-01-13 18:15:52 +0800 | [diff] [blame] | 275 | public: |
| 276 | using Husky::Husky; // Inherit constructors |
Yannick Jadoul | d65e34d | 2020-09-15 14:56:20 +0200 | [diff] [blame] | 277 | std::string go(int n_times) override { PYBIND11_OVERRIDE_PURE(std::string, Husky, go, n_times); } |
| 278 | std::string name() override { PYBIND11_OVERRIDE(std::string, Husky, name, ); } |
| 279 | std::string bark() override { PYBIND11_OVERRIDE(std::string, Husky, bark, ); } |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 280 | }; |
| 281 | |
| 282 | There is, however, a technique that can be used to avoid this duplication |
| 283 | (which can be especially helpful for a base class with several virtual |
| 284 | methods). The technique involves using template trampoline classes, as |
| 285 | follows: |
| 286 | |
| 287 | .. code-block:: cpp |
| 288 | |
| 289 | template <class AnimalBase = Animal> class PyAnimal : public AnimalBase { |
myd7349 | 9b815ad | 2017-01-13 18:15:52 +0800 | [diff] [blame] | 290 | public: |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 291 | using AnimalBase::AnimalBase; // Inherit constructors |
Yannick Jadoul | d65e34d | 2020-09-15 14:56:20 +0200 | [diff] [blame] | 292 | std::string go(int n_times) override { PYBIND11_OVERRIDE_PURE(std::string, AnimalBase, go, n_times); } |
| 293 | std::string name() override { PYBIND11_OVERRIDE(std::string, AnimalBase, name, ); } |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 294 | }; |
| 295 | template <class DogBase = Dog> class PyDog : public PyAnimal<DogBase> { |
myd7349 | 9b815ad | 2017-01-13 18:15:52 +0800 | [diff] [blame] | 296 | public: |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 297 | using PyAnimal<DogBase>::PyAnimal; // Inherit constructors |
| 298 | // Override PyAnimal's pure virtual go() with a non-pure one: |
Yannick Jadoul | d65e34d | 2020-09-15 14:56:20 +0200 | [diff] [blame] | 299 | std::string go(int n_times) override { PYBIND11_OVERRIDE(std::string, DogBase, go, n_times); } |
| 300 | std::string bark() override { PYBIND11_OVERRIDE(std::string, DogBase, bark, ); } |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 301 | }; |
| 302 | |
| 303 | This technique has the advantage of requiring just one trampoline method to be |
| 304 | declared per virtual method and pure virtual method override. It does, |
| 305 | however, require the compiler to generate at least as many methods (and |
| 306 | possibly more, if both pure virtual and overridden pure virtual methods are |
| 307 | exposed, as above). |
| 308 | |
| 309 | The classes are then registered with pybind11 using: |
| 310 | |
| 311 | .. code-block:: cpp |
| 312 | |
| 313 | py::class_<Animal, PyAnimal<>> animal(m, "Animal"); |
Wenzel Jakob | fc3a449 | 2020-07-01 00:25:17 +0200 | [diff] [blame] | 314 | py::class_<Dog, Animal, PyDog<>> dog(m, "Dog"); |
| 315 | py::class_<Husky, Dog, PyDog<Husky>> husky(m, "Husky"); |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 316 | // ... add animal, dog, husky definitions |
| 317 | |
| 318 | Note that ``Husky`` did not require a dedicated trampoline template class at |
| 319 | all, since it neither declares any new virtual methods nor provides any pure |
| 320 | virtual method implementations. |
| 321 | |
| 322 | With either the repeated-virtuals or templated trampoline methods in place, you |
| 323 | can now create a python class that inherits from ``Dog``: |
| 324 | |
| 325 | .. code-block:: python |
| 326 | |
| 327 | class ShihTzu(Dog): |
| 328 | def bark(self): |
| 329 | return "yip!" |
| 330 | |
| 331 | .. seealso:: |
| 332 | |
| 333 | See the file :file:`tests/test_virtual_functions.cpp` for complete examples |
| 334 | using both the duplication and templated trampoline approaches. |
| 335 | |
Jason Rhinelander | 464d989 | 2017-06-12 21:52:48 -0400 | [diff] [blame] | 336 | .. _extended_aliases: |
| 337 | |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 338 | Extended trampoline class functionality |
| 339 | ======================================= |
| 340 | |
Roland Dreier | 7a24bcf | 2019-06-11 01:57:49 -0700 | [diff] [blame] | 341 | .. _extended_class_functionality_forced_trampoline: |
Ivor Wanders | 2b04575 | 2019-06-10 16:12:28 -0400 | [diff] [blame] | 342 | |
| 343 | Forced trampoline class initialisation |
| 344 | -------------------------------------- |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 345 | The trampoline classes described in the previous sections are, by default, only |
| 346 | initialized when needed. More specifically, they are initialized when a python |
| 347 | class actually inherits from a registered type (instead of merely creating an |
| 348 | instance of the registered type), or when a registered constructor is only |
| 349 | valid for the trampoline class but not the registered class. This is primarily |
| 350 | for performance reasons: when the trampoline class is not needed for anything |
| 351 | except virtual method dispatching, not initializing the trampoline class |
| 352 | improves performance by avoiding needing to do a run-time check to see if the |
Yannick Jadoul | d65e34d | 2020-09-15 14:56:20 +0200 | [diff] [blame] | 353 | inheriting python instance has an overridden method. |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 354 | |
| 355 | Sometimes, however, it is useful to always initialize a trampoline class as an |
| 356 | intermediate class that does more than just handle virtual method dispatching. |
| 357 | For example, such a class might perform extra class initialization, extra |
| 358 | destruction operations, and might define new members and methods to enable a |
| 359 | more python-like interface to a class. |
| 360 | |
| 361 | In order to tell pybind11 that it should *always* initialize the trampoline |
| 362 | class when creating new instances of a type, the class constructors should be |
| 363 | declared using ``py::init_alias<Args, ...>()`` instead of the usual |
| 364 | ``py::init<Args, ...>()``. This forces construction via the trampoline class, |
| 365 | ensuring member initialization and (eventual) destruction. |
| 366 | |
| 367 | .. seealso:: |
| 368 | |
Dean Moldovan | 0bc272b | 2017-06-22 23:42:11 +0200 | [diff] [blame] | 369 | See the file :file:`tests/test_virtual_functions.cpp` for complete examples |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 370 | showing both normal and forced trampoline instantiation. |
| 371 | |
Ivor Wanders | 2b04575 | 2019-06-10 16:12:28 -0400 | [diff] [blame] | 372 | Different method signatures |
| 373 | --------------------------- |
| 374 | The macro's introduced in :ref:`overriding_virtuals` cover most of the standard |
| 375 | use cases when exposing C++ classes to Python. Sometimes it is hard or unwieldy |
| 376 | to create a direct one-on-one mapping between the arguments and method return |
| 377 | type. |
| 378 | |
| 379 | An example would be when the C++ signature contains output arguments using |
| 380 | references (See also :ref:`faq_reference_arguments`). Another way of solving |
| 381 | this is to use the method body of the trampoline class to do conversions to the |
| 382 | input and return of the Python method. |
| 383 | |
Yannick Jadoul | d65e34d | 2020-09-15 14:56:20 +0200 | [diff] [blame] | 384 | The main building block to do so is the :func:`get_override`, this function |
Ivor Wanders | 2b04575 | 2019-06-10 16:12:28 -0400 | [diff] [blame] | 385 | allows retrieving a method implemented in Python from within the trampoline's |
| 386 | methods. Consider for example a C++ method which has the signature |
| 387 | ``bool myMethod(int32_t& value)``, where the return indicates whether |
| 388 | something should be done with the ``value``. This can be made convenient on the |
| 389 | Python side by allowing the Python function to return ``None`` or an ``int``: |
| 390 | |
| 391 | .. code-block:: cpp |
| 392 | |
| 393 | bool MyClass::myMethod(int32_t& value) |
| 394 | { |
| 395 | pybind11::gil_scoped_acquire gil; // Acquire the GIL while in this scope. |
Yannick Jadoul | d65e34d | 2020-09-15 14:56:20 +0200 | [diff] [blame] | 396 | // Try to look up the overridden method on the Python side. |
| 397 | pybind11::function override = pybind11::get_override(this, "myMethod"); |
| 398 | if (override) { // method is found |
| 399 | auto obj = override(value); // Call the Python function. |
Ivor Wanders | 2b04575 | 2019-06-10 16:12:28 -0400 | [diff] [blame] | 400 | if (py::isinstance<py::int_>(obj)) { // check if it returned a Python integer type |
| 401 | value = obj.cast<int32_t>(); // Cast it and assign it to the value. |
| 402 | return true; // Return true; value should be used. |
| 403 | } else { |
| 404 | return false; // Python returned none, return false. |
| 405 | } |
| 406 | } |
| 407 | return false; // Alternatively return MyClass::myMethod(value); |
| 408 | } |
| 409 | |
| 410 | |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 411 | .. _custom_constructors: |
| 412 | |
| 413 | Custom constructors |
| 414 | =================== |
| 415 | |
| 416 | The syntax for binding constructors was previously introduced, but it only |
Jason Rhinelander | 464d989 | 2017-06-12 21:52:48 -0400 | [diff] [blame] | 417 | works when a constructor of the appropriate arguments actually exists on the |
Dean Moldovan | 0991d7f | 2017-09-05 16:49:33 +0200 | [diff] [blame] | 418 | C++ side. To extend this to more general cases, pybind11 makes it possible |
| 419 | to bind factory functions as constructors. For example, suppose you have a |
Jason Rhinelander | 464d989 | 2017-06-12 21:52:48 -0400 | [diff] [blame] | 420 | class like this: |
| 421 | |
| 422 | .. code-block:: cpp |
| 423 | |
| 424 | class Example { |
| 425 | private: |
| 426 | Example(int); // private constructor |
| 427 | public: |
| 428 | // Factory function: |
| 429 | static Example create(int a) { return Example(a); } |
| 430 | }; |
| 431 | |
Dean Moldovan | 0991d7f | 2017-09-05 16:49:33 +0200 | [diff] [blame] | 432 | py::class_<Example>(m, "Example") |
| 433 | .def(py::init(&Example::create)); |
| 434 | |
Wenzel Jakob | fb276c6 | 2017-08-22 00:55:53 +0200 | [diff] [blame] | 435 | While it is possible to create a straightforward binding of the static |
| 436 | ``create`` method, it may sometimes be preferable to expose it as a constructor |
| 437 | on the Python side. This can be accomplished by calling ``.def(py::init(...))`` |
| 438 | with the function reference returning the new instance passed as an argument. |
| 439 | It is also possible to use this approach to bind a function returning a new |
| 440 | instance by raw pointer or by the holder (e.g. ``std::unique_ptr``). |
Jason Rhinelander | 464d989 | 2017-06-12 21:52:48 -0400 | [diff] [blame] | 441 | |
| 442 | The following example shows the different approaches: |
| 443 | |
| 444 | .. code-block:: cpp |
| 445 | |
| 446 | class Example { |
| 447 | private: |
| 448 | Example(int); // private constructor |
| 449 | public: |
| 450 | // Factory function - returned by value: |
| 451 | static Example create(int a) { return Example(a); } |
| 452 | |
| 453 | // These constructors are publicly callable: |
| 454 | Example(double); |
| 455 | Example(int, int); |
| 456 | Example(std::string); |
| 457 | }; |
| 458 | |
| 459 | py::class_<Example>(m, "Example") |
| 460 | // Bind the factory function as a constructor: |
| 461 | .def(py::init(&Example::create)) |
| 462 | // Bind a lambda function returning a pointer wrapped in a holder: |
| 463 | .def(py::init([](std::string arg) { |
| 464 | return std::unique_ptr<Example>(new Example(arg)); |
| 465 | })) |
| 466 | // Return a raw pointer: |
| 467 | .def(py::init([](int a, int b) { return new Example(a, b); })) |
| 468 | // You can mix the above with regular C++ constructor bindings as well: |
| 469 | .def(py::init<double>()) |
| 470 | ; |
| 471 | |
| 472 | When the constructor is invoked from Python, pybind11 will call the factory |
| 473 | function and store the resulting C++ instance in the Python instance. |
| 474 | |
Wenzel Jakob | fb276c6 | 2017-08-22 00:55:53 +0200 | [diff] [blame] | 475 | When combining factory functions constructors with :ref:`virtual function |
| 476 | trampolines <overriding_virtuals>` there are two approaches. The first is to |
| 477 | add a constructor to the alias class that takes a base value by |
| 478 | rvalue-reference. If such a constructor is available, it will be used to |
| 479 | construct an alias instance from the value returned by the factory function. |
| 480 | The second option is to provide two factory functions to ``py::init()``: the |
| 481 | first will be invoked when no alias class is required (i.e. when the class is |
| 482 | being used but not inherited from in Python), and the second will be invoked |
| 483 | when an alias is required. |
Jason Rhinelander | 464d989 | 2017-06-12 21:52:48 -0400 | [diff] [blame] | 484 | |
| 485 | You can also specify a single factory function that always returns an alias |
| 486 | instance: this will result in behaviour similar to ``py::init_alias<...>()``, |
Wenzel Jakob | fb276c6 | 2017-08-22 00:55:53 +0200 | [diff] [blame] | 487 | as described in the :ref:`extended trampoline class documentation |
| 488 | <extended_aliases>`. |
Jason Rhinelander | 464d989 | 2017-06-12 21:52:48 -0400 | [diff] [blame] | 489 | |
| 490 | The following example shows the different factory approaches for a class with |
| 491 | an alias: |
| 492 | |
| 493 | .. code-block:: cpp |
| 494 | |
| 495 | #include <pybind11/factory.h> |
| 496 | class Example { |
| 497 | public: |
| 498 | // ... |
| 499 | virtual ~Example() = default; |
| 500 | }; |
| 501 | class PyExample : public Example { |
| 502 | public: |
| 503 | using Example::Example; |
| 504 | PyExample(Example &&base) : Example(std::move(base)) {} |
| 505 | }; |
| 506 | py::class_<Example, PyExample>(m, "Example") |
| 507 | // Returns an Example pointer. If a PyExample is needed, the Example |
| 508 | // instance will be moved via the extra constructor in PyExample, above. |
| 509 | .def(py::init([]() { return new Example(); })) |
| 510 | // Two callbacks: |
| 511 | .def(py::init([]() { return new Example(); } /* no alias needed */, |
| 512 | []() { return new PyExample(); } /* alias needed */)) |
| 513 | // *Always* returns an alias instance (like py::init_alias<>()) |
| 514 | .def(py::init([]() { return new PyExample(); })) |
| 515 | ; |
| 516 | |
Wenzel Jakob | 4336a7d | 2017-08-21 22:48:28 +0200 | [diff] [blame] | 517 | Brace initialization |
| 518 | -------------------- |
| 519 | |
| 520 | ``pybind11::init<>`` internally uses C++11 brace initialization to call the |
| 521 | constructor of the target class. This means that it can be used to bind |
| 522 | *implicit* constructors as well: |
| 523 | |
| 524 | .. code-block:: cpp |
| 525 | |
| 526 | struct Aggregate { |
| 527 | int a; |
| 528 | std::string b; |
| 529 | }; |
| 530 | |
| 531 | py::class_<Aggregate>(m, "Aggregate") |
| 532 | .def(py::init<int, const std::string &>()); |
| 533 | |
| 534 | .. note:: |
| 535 | |
| 536 | Note that brace initialization preferentially invokes constructor overloads |
| 537 | taking a ``std::initializer_list``. In the rare event that this causes an |
| 538 | issue, you can work around it by using ``py::init(...)`` with a lambda |
| 539 | function that constructs the new object as desired. |
| 540 | |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 541 | .. _classes_with_non_public_destructors: |
| 542 | |
| 543 | Non-public destructors |
| 544 | ====================== |
| 545 | |
| 546 | If a class has a private or protected destructor (as might e.g. be the case in |
| 547 | a singleton pattern), a compile error will occur when creating bindings via |
| 548 | pybind11. The underlying issue is that the ``std::unique_ptr`` holder type that |
| 549 | is responsible for managing the lifetime of instances will reference the |
| 550 | destructor even if no deallocations ever take place. In order to expose classes |
| 551 | with private or protected destructors, it is possible to override the holder |
| 552 | type via a holder type argument to ``class_``. Pybind11 provides a helper class |
| 553 | ``py::nodelete`` that disables any destructor invocations. In this case, it is |
| 554 | crucial that instances are deallocated on the C++ side to avoid memory leaks. |
| 555 | |
| 556 | .. code-block:: cpp |
| 557 | |
| 558 | /* ... definition ... */ |
| 559 | |
| 560 | class MyClass { |
| 561 | private: |
| 562 | ~MyClass() { } |
| 563 | }; |
| 564 | |
| 565 | /* ... binding code ... */ |
| 566 | |
| 567 | py::class_<MyClass, std::unique_ptr<MyClass, py::nodelete>>(m, "MyClass") |
myd7349 | 9b815ad | 2017-01-13 18:15:52 +0800 | [diff] [blame] | 568 | .def(py::init<>()) |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 569 | |
James R. Barlow | 3618bea | 2020-08-08 03:07:14 -0700 | [diff] [blame] | 570 | .. _destructors_that_call_python: |
| 571 | |
| 572 | Destructors that call Python |
| 573 | ============================ |
| 574 | |
| 575 | If a Python function is invoked from a C++ destructor, an exception may be thrown |
| 576 | of type :class:`error_already_set`. If this error is thrown out of a class destructor, |
| 577 | ``std::terminate()`` will be called, terminating the process. Class destructors |
| 578 | must catch all exceptions of type :class:`error_already_set` to discard the Python |
| 579 | exception using :func:`error_already_set::discard_as_unraisable`. |
| 580 | |
| 581 | Every Python function should be treated as *possibly throwing*. When a Python generator |
| 582 | stops yielding items, Python will throw a ``StopIteration`` exception, which can pass |
| 583 | though C++ destructors if the generator's stack frame holds the last reference to C++ |
| 584 | objects. |
| 585 | |
| 586 | For more information, see :ref:`the documentation on exceptions <unraisable_exceptions>`. |
| 587 | |
| 588 | .. code-block:: cpp |
| 589 | |
| 590 | class MyClass { |
| 591 | public: |
| 592 | ~MyClass() { |
| 593 | try { |
| 594 | py::print("Even printing is dangerous in a destructor"); |
| 595 | py::exec("raise ValueError('This is an unraisable exception')"); |
| 596 | } catch (py::error_already_set &e) { |
| 597 | // error_context should be information about where/why the occurred, |
| 598 | // e.g. use __func__ to get the name of the current function |
| 599 | e.discard_as_unraisable(__func__); |
| 600 | } |
| 601 | } |
| 602 | }; |
| 603 | |
| 604 | .. note:: |
| 605 | |
| 606 | pybind11 does not support C++ destructors marked ``noexcept(false)``. |
| 607 | |
Henry Schreiner | a6887b6 | 2020-08-19 14:53:59 -0400 | [diff] [blame] | 608 | .. versionadded:: 2.6 |
| 609 | |
Jason Rhinelander | abc29ca | 2017-01-23 03:50:00 -0500 | [diff] [blame] | 610 | .. _implicit_conversions: |
| 611 | |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 612 | Implicit conversions |
| 613 | ==================== |
| 614 | |
| 615 | Suppose that instances of two types ``A`` and ``B`` are used in a project, and |
| 616 | that an ``A`` can easily be converted into an instance of type ``B`` (examples of this |
| 617 | could be a fixed and an arbitrary precision number type). |
| 618 | |
| 619 | .. code-block:: cpp |
| 620 | |
| 621 | py::class_<A>(m, "A") |
| 622 | /// ... members ... |
| 623 | |
| 624 | py::class_<B>(m, "B") |
| 625 | .def(py::init<A>()) |
| 626 | /// ... members ... |
| 627 | |
| 628 | m.def("func", |
| 629 | [](const B &) { /* .... */ } |
| 630 | ); |
| 631 | |
| 632 | To invoke the function ``func`` using a variable ``a`` containing an ``A`` |
| 633 | instance, we'd have to write ``func(B(a))`` in Python. On the other hand, C++ |
| 634 | will automatically apply an implicit type conversion, which makes it possible |
| 635 | to directly write ``func(a)``. |
| 636 | |
| 637 | In this situation (i.e. where ``B`` has a constructor that converts from |
| 638 | ``A``), the following statement enables similar implicit conversions on the |
| 639 | Python side: |
| 640 | |
| 641 | .. code-block:: cpp |
| 642 | |
| 643 | py::implicitly_convertible<A, B>(); |
| 644 | |
| 645 | .. note:: |
| 646 | |
| 647 | Implicit conversions from ``A`` to ``B`` only work when ``B`` is a custom |
| 648 | data type that is exposed to Python via pybind11. |
| 649 | |
Wenzel Jakob | 8ed5b8a | 2017-08-28 16:34:06 +0200 | [diff] [blame] | 650 | To prevent runaway recursion, implicit conversions are non-reentrant: an |
| 651 | implicit conversion invoked as part of another implicit conversion of the |
| 652 | same type (i.e. from ``A`` to ``B``) will fail. |
| 653 | |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 654 | .. _static_properties: |
| 655 | |
| 656 | Static properties |
| 657 | ================= |
| 658 | |
| 659 | The section on :ref:`properties` discussed the creation of instance properties |
| 660 | that are implemented in terms of C++ getters and setters. |
| 661 | |
| 662 | Static properties can also be created in a similar way to expose getters and |
Dean Moldovan | dd01665 | 2017-02-16 23:02:56 +0100 | [diff] [blame] | 663 | setters of static class attributes. Note that the implicit ``self`` argument |
| 664 | also exists in this case and is used to pass the Python ``type`` subclass |
| 665 | instance. This parameter will often not be needed by the C++ side, and the |
| 666 | following example illustrates how to instantiate a lambda getter function |
| 667 | that ignores it: |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 668 | |
| 669 | .. code-block:: cpp |
| 670 | |
Dean Moldovan | dd01665 | 2017-02-16 23:02:56 +0100 | [diff] [blame] | 671 | py::class_<Foo>(m, "Foo") |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 672 | .def_property_readonly_static("foo", [](py::object /* self */) { return Foo(); }); |
| 673 | |
| 674 | Operator overloading |
| 675 | ==================== |
| 676 | |
| 677 | Suppose that we're given the following ``Vector2`` class with a vector addition |
| 678 | and scalar multiplication operation, all implemented using overloaded operators |
| 679 | in C++. |
| 680 | |
| 681 | .. code-block:: cpp |
| 682 | |
| 683 | class Vector2 { |
| 684 | public: |
| 685 | Vector2(float x, float y) : x(x), y(y) { } |
| 686 | |
| 687 | Vector2 operator+(const Vector2 &v) const { return Vector2(x + v.x, y + v.y); } |
| 688 | Vector2 operator*(float value) const { return Vector2(x * value, y * value); } |
| 689 | Vector2& operator+=(const Vector2 &v) { x += v.x; y += v.y; return *this; } |
| 690 | Vector2& operator*=(float v) { x *= v; y *= v; return *this; } |
| 691 | |
| 692 | friend Vector2 operator*(float f, const Vector2 &v) { |
| 693 | return Vector2(f * v.x, f * v.y); |
| 694 | } |
| 695 | |
| 696 | std::string toString() const { |
| 697 | return "[" + std::to_string(x) + ", " + std::to_string(y) + "]"; |
| 698 | } |
| 699 | private: |
| 700 | float x, y; |
| 701 | }; |
| 702 | |
| 703 | The following snippet shows how the above operators can be conveniently exposed |
| 704 | to Python. |
| 705 | |
| 706 | .. code-block:: cpp |
| 707 | |
| 708 | #include <pybind11/operators.h> |
| 709 | |
Dean Moldovan | 443ab59 | 2017-04-24 01:51:44 +0200 | [diff] [blame] | 710 | PYBIND11_MODULE(example, m) { |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 711 | py::class_<Vector2>(m, "Vector2") |
| 712 | .def(py::init<float, float>()) |
| 713 | .def(py::self + py::self) |
| 714 | .def(py::self += py::self) |
| 715 | .def(py::self *= float()) |
| 716 | .def(float() * py::self) |
myd7349 | 9b815ad | 2017-01-13 18:15:52 +0800 | [diff] [blame] | 717 | .def(py::self * float()) |
Ian Bell | 502ffe5 | 2019-06-22 04:07:41 -0600 | [diff] [blame] | 718 | .def(-py::self) |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 719 | .def("__repr__", &Vector2::toString); |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 720 | } |
| 721 | |
| 722 | Note that a line like |
| 723 | |
| 724 | .. code-block:: cpp |
| 725 | |
| 726 | .def(py::self * float()) |
| 727 | |
| 728 | is really just short hand notation for |
| 729 | |
| 730 | .. code-block:: cpp |
| 731 | |
| 732 | .def("__mul__", [](const Vector2 &a, float b) { |
| 733 | return a * b; |
| 734 | }, py::is_operator()) |
| 735 | |
| 736 | This can be useful for exposing additional operators that don't exist on the |
| 737 | C++ side, or to perform other types of customization. The ``py::is_operator`` |
| 738 | flag marker is needed to inform pybind11 that this is an operator, which |
| 739 | returns ``NotImplemented`` when invoked with incompatible arguments rather than |
| 740 | throwing a type error. |
| 741 | |
| 742 | .. note:: |
| 743 | |
| 744 | To use the more convenient ``py::self`` notation, the additional |
| 745 | header file :file:`pybind11/operators.h` must be included. |
| 746 | |
| 747 | .. seealso:: |
| 748 | |
| 749 | The file :file:`tests/test_operator_overloading.cpp` contains a |
| 750 | complete example that demonstrates how to work with overloaded operators in |
| 751 | more detail. |
| 752 | |
Dean Moldovan | 1e5a7da | 2017-08-24 01:53:15 +0200 | [diff] [blame] | 753 | .. _pickling: |
| 754 | |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 755 | Pickling support |
| 756 | ================ |
| 757 | |
| 758 | Python's ``pickle`` module provides a powerful facility to serialize and |
| 759 | de-serialize a Python object graph into a binary data stream. To pickle and |
Dean Moldovan | 1e5a7da | 2017-08-24 01:53:15 +0200 | [diff] [blame] | 760 | unpickle C++ classes using pybind11, a ``py::pickle()`` definition must be |
| 761 | provided. Suppose the class in question has the following signature: |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 762 | |
| 763 | .. code-block:: cpp |
| 764 | |
| 765 | class Pickleable { |
| 766 | public: |
| 767 | Pickleable(const std::string &value) : m_value(value) { } |
| 768 | const std::string &value() const { return m_value; } |
| 769 | |
| 770 | void setExtra(int extra) { m_extra = extra; } |
| 771 | int extra() const { return m_extra; } |
| 772 | private: |
| 773 | std::string m_value; |
| 774 | int m_extra = 0; |
| 775 | }; |
| 776 | |
Patrik Huber | 1ad2227 | 2017-09-04 22:00:19 +0100 | [diff] [blame] | 777 | Pickling support in Python is enabled by defining the ``__setstate__`` and |
Dean Moldovan | 1e5a7da | 2017-08-24 01:53:15 +0200 | [diff] [blame] | 778 | ``__getstate__`` methods [#f3]_. For pybind11 classes, use ``py::pickle()`` |
| 779 | to bind these two functions: |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 780 | |
| 781 | .. code-block:: cpp |
| 782 | |
| 783 | py::class_<Pickleable>(m, "Pickleable") |
| 784 | .def(py::init<std::string>()) |
| 785 | .def("value", &Pickleable::value) |
| 786 | .def("extra", &Pickleable::extra) |
| 787 | .def("setExtra", &Pickleable::setExtra) |
Dean Moldovan | 1e5a7da | 2017-08-24 01:53:15 +0200 | [diff] [blame] | 788 | .def(py::pickle( |
| 789 | [](const Pickleable &p) { // __getstate__ |
| 790 | /* Return a tuple that fully encodes the state of the object */ |
| 791 | return py::make_tuple(p.value(), p.extra()); |
| 792 | }, |
| 793 | [](py::tuple t) { // __setstate__ |
| 794 | if (t.size() != 2) |
| 795 | throw std::runtime_error("Invalid state!"); |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 796 | |
Dean Moldovan | 1e5a7da | 2017-08-24 01:53:15 +0200 | [diff] [blame] | 797 | /* Create a new C++ instance */ |
| 798 | Pickleable p(t[0].cast<std::string>()); |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 799 | |
Dean Moldovan | 1e5a7da | 2017-08-24 01:53:15 +0200 | [diff] [blame] | 800 | /* Assign any additional state */ |
| 801 | p.setExtra(t[1].cast<int>()); |
| 802 | |
| 803 | return p; |
| 804 | } |
| 805 | )); |
| 806 | |
| 807 | The ``__setstate__`` part of the ``py::picke()`` definition follows the same |
| 808 | rules as the single-argument version of ``py::init()``. The return type can be |
| 809 | a value, pointer or holder type. See :ref:`custom_constructors` for details. |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 810 | |
| 811 | An instance can now be pickled as follows: |
| 812 | |
| 813 | .. code-block:: python |
| 814 | |
| 815 | try: |
| 816 | import cPickle as pickle # Use cPickle on Python 2.7 |
| 817 | except ImportError: |
| 818 | import pickle |
| 819 | |
| 820 | p = Pickleable("test_value") |
| 821 | p.setExtra(15) |
| 822 | data = pickle.dumps(p, 2) |
| 823 | |
Matthijs van der Burgh | b524008 | 2020-06-10 13:30:41 +0200 | [diff] [blame] | 824 | |
| 825 | .. note:: |
| 826 | Note that only the cPickle module is supported on Python 2.7. |
| 827 | |
| 828 | The second argument to ``dumps`` is also crucial: it selects the pickle |
| 829 | protocol version 2, since the older version 1 is not supported. Newer |
| 830 | versions are also fine—for instance, specify ``-1`` to always use the |
| 831 | latest available version. Beware: failure to follow these instructions |
| 832 | will cause important pybind11 memory allocation routines to be skipped |
| 833 | during unpickling, which will likely lead to memory corruption and/or |
| 834 | segmentation faults. |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 835 | |
| 836 | .. seealso:: |
| 837 | |
| 838 | The file :file:`tests/test_pickling.cpp` contains a complete example |
| 839 | that demonstrates how to pickle and unpickle types using pybind11 in more |
| 840 | detail. |
| 841 | |
| 842 | .. [#f3] http://docs.python.org/3/library/pickle.html#pickling-class-instances |
| 843 | |
Matthijs van der Burgh | b524008 | 2020-06-10 13:30:41 +0200 | [diff] [blame] | 844 | Deepcopy support |
| 845 | ================ |
| 846 | |
| 847 | Python normally uses references in assignments. Sometimes a real copy is needed |
| 848 | to prevent changing all copies. The ``copy`` module [#f5]_ provides these |
| 849 | capabilities. |
| 850 | |
| 851 | On Python 3, a class with pickle support is automatically also (deep)copy |
| 852 | compatible. However, performance can be improved by adding custom |
| 853 | ``__copy__`` and ``__deepcopy__`` methods. With Python 2.7, these custom methods |
| 854 | are mandatory for (deep)copy compatibility, because pybind11 only supports |
| 855 | cPickle. |
| 856 | |
| 857 | For simple classes (deep)copy can be enabled by using the copy constructor, |
| 858 | which should look as follows: |
| 859 | |
| 860 | .. code-block:: cpp |
| 861 | |
| 862 | py::class_<Copyable>(m, "Copyable") |
| 863 | .def("__copy__", [](const Copyable &self) { |
| 864 | return Copyable(self); |
| 865 | }) |
| 866 | .def("__deepcopy__", [](const Copyable &self, py::dict) { |
| 867 | return Copyable(self); |
| 868 | }, "memo"_a); |
| 869 | |
| 870 | .. note:: |
| 871 | |
| 872 | Dynamic attributes will not be copied in this example. |
| 873 | |
| 874 | .. [#f5] https://docs.python.org/3/library/copy.html |
| 875 | |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 876 | Multiple Inheritance |
| 877 | ==================== |
| 878 | |
| 879 | pybind11 can create bindings for types that derive from multiple base types |
| 880 | (aka. *multiple inheritance*). To do so, specify all bases in the template |
| 881 | arguments of the ``class_`` declaration: |
| 882 | |
| 883 | .. code-block:: cpp |
| 884 | |
| 885 | py::class_<MyType, BaseType1, BaseType2, BaseType3>(m, "MyType") |
| 886 | ... |
| 887 | |
| 888 | The base types can be specified in arbitrary order, and they can even be |
| 889 | interspersed with alias types and holder types (discussed earlier in this |
| 890 | document)---pybind11 will automatically find out which is which. The only |
| 891 | requirement is that the first template argument is the type to be declared. |
| 892 | |
Jason Rhinelander | e45c211 | 2017-02-22 21:36:09 -0500 | [diff] [blame] | 893 | It is also permitted to inherit multiply from exported C++ classes in Python, |
Tom de Geus | a7ff616 | 2018-05-04 17:04:45 +0200 | [diff] [blame] | 894 | as well as inheriting from multiple Python and/or pybind11-exported classes. |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 895 | |
Jason Rhinelander | e45c211 | 2017-02-22 21:36:09 -0500 | [diff] [blame] | 896 | There is one caveat regarding the implementation of this feature: |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 897 | |
Jason Rhinelander | e45c211 | 2017-02-22 21:36:09 -0500 | [diff] [blame] | 898 | When only one base type is specified for a C++ type that actually has multiple |
| 899 | bases, pybind11 will assume that it does not participate in multiple |
| 900 | inheritance, which can lead to undefined behavior. In such cases, add the tag |
| 901 | ``multiple_inheritance`` to the class constructor: |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 902 | |
Jason Rhinelander | e45c211 | 2017-02-22 21:36:09 -0500 | [diff] [blame] | 903 | .. code-block:: cpp |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 904 | |
Jason Rhinelander | e45c211 | 2017-02-22 21:36:09 -0500 | [diff] [blame] | 905 | py::class_<MyType, BaseType2>(m, "MyType", py::multiple_inheritance()); |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 906 | |
Jason Rhinelander | e45c211 | 2017-02-22 21:36:09 -0500 | [diff] [blame] | 907 | The tag is redundant and does not need to be specified when multiple base types |
| 908 | are listed. |
Jason Rhinelander | 7437c69 | 2017-07-28 22:03:44 -0400 | [diff] [blame] | 909 | |
| 910 | .. _module_local: |
| 911 | |
| 912 | Module-local class bindings |
| 913 | =========================== |
| 914 | |
Tom de Geus | a7ff616 | 2018-05-04 17:04:45 +0200 | [diff] [blame] | 915 | When creating a binding for a class, pybind11 by default makes that binding |
Jason Rhinelander | 7437c69 | 2017-07-28 22:03:44 -0400 | [diff] [blame] | 916 | "global" across modules. What this means is that a type defined in one module |
Jason Rhinelander | 5e14aa6 | 2017-08-17 11:38:05 -0400 | [diff] [blame] | 917 | can be returned from any module resulting in the same Python type. For |
Jason Rhinelander | 7437c69 | 2017-07-28 22:03:44 -0400 | [diff] [blame] | 918 | example, this allows the following: |
| 919 | |
| 920 | .. code-block:: cpp |
| 921 | |
| 922 | // In the module1.cpp binding code for module1: |
| 923 | py::class_<Pet>(m, "Pet") |
Jason Rhinelander | 5e14aa6 | 2017-08-17 11:38:05 -0400 | [diff] [blame] | 924 | .def(py::init<std::string>()) |
| 925 | .def_readonly("name", &Pet::name); |
Jason Rhinelander | 7437c69 | 2017-07-28 22:03:44 -0400 | [diff] [blame] | 926 | |
| 927 | .. code-block:: cpp |
| 928 | |
| 929 | // In the module2.cpp binding code for module2: |
Jason Rhinelander | 5e14aa6 | 2017-08-17 11:38:05 -0400 | [diff] [blame] | 930 | m.def("create_pet", [](std::string name) { return new Pet(name); }); |
Jason Rhinelander | 7437c69 | 2017-07-28 22:03:44 -0400 | [diff] [blame] | 931 | |
| 932 | .. code-block:: pycon |
| 933 | |
| 934 | >>> from module1 import Pet |
Jason Rhinelander | 5e14aa6 | 2017-08-17 11:38:05 -0400 | [diff] [blame] | 935 | >>> from module2 import create_pet |
| 936 | >>> pet1 = Pet("Kitty") |
| 937 | >>> pet2 = create_pet("Doggy") |
| 938 | >>> pet2.name() |
| 939 | 'Doggy' |
Jason Rhinelander | 7437c69 | 2017-07-28 22:03:44 -0400 | [diff] [blame] | 940 | |
| 941 | When writing binding code for a library, this is usually desirable: this |
| 942 | allows, for example, splitting up a complex library into multiple Python |
| 943 | modules. |
| 944 | |
| 945 | In some cases, however, this can cause conflicts. For example, suppose two |
| 946 | unrelated modules make use of an external C++ library and each provide custom |
| 947 | bindings for one of that library's classes. This will result in an error when |
| 948 | a Python program attempts to import both modules (directly or indirectly) |
| 949 | because of conflicting definitions on the external type: |
| 950 | |
| 951 | .. code-block:: cpp |
| 952 | |
| 953 | // dogs.cpp |
| 954 | |
| 955 | // Binding for external library class: |
| 956 | py::class<pets::Pet>(m, "Pet") |
| 957 | .def("name", &pets::Pet::name); |
| 958 | |
| 959 | // Binding for local extension class: |
| 960 | py::class<Dog, pets::Pet>(m, "Dog") |
| 961 | .def(py::init<std::string>()); |
| 962 | |
| 963 | .. code-block:: cpp |
| 964 | |
| 965 | // cats.cpp, in a completely separate project from the above dogs.cpp. |
| 966 | |
| 967 | // Binding for external library class: |
| 968 | py::class<pets::Pet>(m, "Pet") |
| 969 | .def("get_name", &pets::Pet::name); |
| 970 | |
| 971 | // Binding for local extending class: |
| 972 | py::class<Cat, pets::Pet>(m, "Cat") |
| 973 | .def(py::init<std::string>()); |
| 974 | |
| 975 | .. code-block:: pycon |
| 976 | |
| 977 | >>> import cats |
| 978 | >>> import dogs |
| 979 | Traceback (most recent call last): |
| 980 | File "<stdin>", line 1, in <module> |
| 981 | ImportError: generic_type: type "Pet" is already registered! |
| 982 | |
| 983 | To get around this, you can tell pybind11 to keep the external class binding |
| 984 | localized to the module by passing the ``py::module_local()`` attribute into |
| 985 | the ``py::class_`` constructor: |
| 986 | |
| 987 | .. code-block:: cpp |
| 988 | |
| 989 | // Pet binding in dogs.cpp: |
| 990 | py::class<pets::Pet>(m, "Pet", py::module_local()) |
| 991 | .def("name", &pets::Pet::name); |
| 992 | |
| 993 | .. code-block:: cpp |
| 994 | |
| 995 | // Pet binding in cats.cpp: |
| 996 | py::class<pets::Pet>(m, "Pet", py::module_local()) |
| 997 | .def("get_name", &pets::Pet::name); |
| 998 | |
Jason Rhinelander | 5e14aa6 | 2017-08-17 11:38:05 -0400 | [diff] [blame] | 999 | This makes the Python-side ``dogs.Pet`` and ``cats.Pet`` into distinct classes, |
| 1000 | avoiding the conflict and allowing both modules to be loaded. C++ code in the |
| 1001 | ``dogs`` module that casts or returns a ``Pet`` instance will result in a |
| 1002 | ``dogs.Pet`` Python instance, while C++ code in the ``cats`` module will result |
| 1003 | in a ``cats.Pet`` Python instance. |
Jason Rhinelander | 7437c69 | 2017-07-28 22:03:44 -0400 | [diff] [blame] | 1004 | |
Jason Rhinelander | 5e14aa6 | 2017-08-17 11:38:05 -0400 | [diff] [blame] | 1005 | This does come with two caveats, however: First, external modules cannot return |
| 1006 | or cast a ``Pet`` instance to Python (unless they also provide their own local |
| 1007 | bindings). Second, from the Python point of view they are two distinct classes. |
| 1008 | |
| 1009 | Note that the locality only applies in the C++ -> Python direction. When |
| 1010 | passing such a ``py::module_local`` type into a C++ function, the module-local |
| 1011 | classes are still considered. This means that if the following function is |
| 1012 | added to any module (including but not limited to the ``cats`` and ``dogs`` |
| 1013 | modules above) it will be callable with either a ``dogs.Pet`` or ``cats.Pet`` |
| 1014 | argument: |
Jason Rhinelander | 7437c69 | 2017-07-28 22:03:44 -0400 | [diff] [blame] | 1015 | |
| 1016 | .. code-block:: cpp |
| 1017 | |
Jason Rhinelander | 5e14aa6 | 2017-08-17 11:38:05 -0400 | [diff] [blame] | 1018 | m.def("pet_name", [](const pets::Pet &pet) { return pet.name(); }); |
Jason Rhinelander | 7437c69 | 2017-07-28 22:03:44 -0400 | [diff] [blame] | 1019 | |
Jason Rhinelander | 5e14aa6 | 2017-08-17 11:38:05 -0400 | [diff] [blame] | 1020 | For example, suppose the above function is added to each of ``cats.cpp``, |
| 1021 | ``dogs.cpp`` and ``frogs.cpp`` (where ``frogs.cpp`` is some other module that |
| 1022 | does *not* bind ``Pets`` at all). |
Jason Rhinelander | 7437c69 | 2017-07-28 22:03:44 -0400 | [diff] [blame] | 1023 | |
| 1024 | .. code-block:: pycon |
| 1025 | |
Jason Rhinelander | 5e14aa6 | 2017-08-17 11:38:05 -0400 | [diff] [blame] | 1026 | >>> import cats, dogs, frogs # No error because of the added py::module_local() |
Jason Rhinelander | 7437c69 | 2017-07-28 22:03:44 -0400 | [diff] [blame] | 1027 | >>> mycat, mydog = cats.Cat("Fluffy"), dogs.Dog("Rover") |
Jason Rhinelander | 5e14aa6 | 2017-08-17 11:38:05 -0400 | [diff] [blame] | 1028 | >>> (cats.pet_name(mycat), dogs.pet_name(mydog)) |
Jason Rhinelander | 7437c69 | 2017-07-28 22:03:44 -0400 | [diff] [blame] | 1029 | ('Fluffy', 'Rover') |
Jason Rhinelander | 5e14aa6 | 2017-08-17 11:38:05 -0400 | [diff] [blame] | 1030 | >>> (cats.pet_name(mydog), dogs.pet_name(mycat), frogs.pet_name(mycat)) |
| 1031 | ('Rover', 'Fluffy', 'Fluffy') |
Jason Rhinelander | 7437c69 | 2017-07-28 22:03:44 -0400 | [diff] [blame] | 1032 | |
Jason Rhinelander | 5e14aa6 | 2017-08-17 11:38:05 -0400 | [diff] [blame] | 1033 | It is possible to use ``py::module_local()`` registrations in one module even |
| 1034 | if another module registers the same type globally: within the module with the |
| 1035 | module-local definition, all C++ instances will be cast to the associated bound |
| 1036 | Python type. In other modules any such values are converted to the global |
| 1037 | Python type created elsewhere. |
Jason Rhinelander | 4b15923 | 2017-08-04 13:05:12 -0400 | [diff] [blame] | 1038 | |
Jason Rhinelander | 7437c69 | 2017-07-28 22:03:44 -0400 | [diff] [blame] | 1039 | .. note:: |
| 1040 | |
| 1041 | STL bindings (as provided via the optional :file:`pybind11/stl_bind.h` |
| 1042 | header) apply ``py::module_local`` by default when the bound type might |
| 1043 | conflict with other modules; see :ref:`stl_bind` for details. |
| 1044 | |
| 1045 | .. note:: |
| 1046 | |
| 1047 | The localization of the bound types is actually tied to the shared object |
| 1048 | or binary generated by the compiler/linker. For typical modules created |
| 1049 | with ``PYBIND11_MODULE()``, this distinction is not significant. It is |
| 1050 | possible, however, when :ref:`embedding` to embed multiple modules in the |
| 1051 | same binary (see :ref:`embedding_modules`). In such a case, the |
| 1052 | localization will apply across all embedded modules within the same binary. |
| 1053 | |
| 1054 | .. seealso:: |
| 1055 | |
| 1056 | The file :file:`tests/test_local_bindings.cpp` contains additional examples |
| 1057 | that demonstrate how ``py::module_local()`` works. |
Dean Moldovan | 234f7c3 | 2017-08-17 17:03:46 +0200 | [diff] [blame] | 1058 | |
| 1059 | Binding protected member functions |
| 1060 | ================================== |
| 1061 | |
| 1062 | It's normally not possible to expose ``protected`` member functions to Python: |
| 1063 | |
| 1064 | .. code-block:: cpp |
| 1065 | |
| 1066 | class A { |
| 1067 | protected: |
| 1068 | int foo() const { return 42; } |
| 1069 | }; |
| 1070 | |
| 1071 | py::class_<A>(m, "A") |
| 1072 | .def("foo", &A::foo); // error: 'foo' is a protected member of 'A' |
| 1073 | |
| 1074 | On one hand, this is good because non-``public`` members aren't meant to be |
| 1075 | accessed from the outside. But we may want to make use of ``protected`` |
| 1076 | functions in derived Python classes. |
| 1077 | |
| 1078 | The following pattern makes this possible: |
| 1079 | |
| 1080 | .. code-block:: cpp |
| 1081 | |
| 1082 | class A { |
| 1083 | protected: |
| 1084 | int foo() const { return 42; } |
| 1085 | }; |
| 1086 | |
| 1087 | class Publicist : public A { // helper type for exposing protected functions |
| 1088 | public: |
| 1089 | using A::foo; // inherited with different access modifier |
| 1090 | }; |
| 1091 | |
| 1092 | py::class_<A>(m, "A") // bind the primary class |
| 1093 | .def("foo", &Publicist::foo); // expose protected methods via the publicist |
| 1094 | |
| 1095 | This works because ``&Publicist::foo`` is exactly the same function as |
| 1096 | ``&A::foo`` (same signature and address), just with a different access |
| 1097 | modifier. The only purpose of the ``Publicist`` helper class is to make |
| 1098 | the function name ``public``. |
| 1099 | |
| 1100 | If the intent is to expose ``protected`` ``virtual`` functions which can be |
| 1101 | overridden in Python, the publicist pattern can be combined with the previously |
| 1102 | described trampoline: |
| 1103 | |
| 1104 | .. code-block:: cpp |
| 1105 | |
| 1106 | class A { |
| 1107 | public: |
| 1108 | virtual ~A() = default; |
| 1109 | |
| 1110 | protected: |
| 1111 | virtual int foo() const { return 42; } |
| 1112 | }; |
| 1113 | |
| 1114 | class Trampoline : public A { |
| 1115 | public: |
Yannick Jadoul | d65e34d | 2020-09-15 14:56:20 +0200 | [diff] [blame] | 1116 | int foo() const override { PYBIND11_OVERRIDE(int, A, foo, ); } |
Dean Moldovan | 234f7c3 | 2017-08-17 17:03:46 +0200 | [diff] [blame] | 1117 | }; |
| 1118 | |
| 1119 | class Publicist : public A { |
| 1120 | public: |
| 1121 | using A::foo; |
| 1122 | }; |
| 1123 | |
| 1124 | py::class_<A, Trampoline>(m, "A") // <-- `Trampoline` here |
| 1125 | .def("foo", &Publicist::foo); // <-- `Publicist` here, not `Trampoline`! |
| 1126 | |
| 1127 | .. note:: |
| 1128 | |
| 1129 | MSVC 2015 has a compiler bug (fixed in version 2017) which |
| 1130 | requires a more explicit function binding in the form of |
| 1131 | ``.def("foo", static_cast<int (A::*)() const>(&Publicist::foo));`` |
| 1132 | where ``int (A::*)() const`` is the type of ``A::foo``. |
oremanj | fd9bc8f | 2018-04-13 20:13:10 -0400 | [diff] [blame] | 1133 | |
Dustin Spicuzza | 0dfffcf | 2020-04-05 02:34:00 -0400 | [diff] [blame] | 1134 | Binding final classes |
| 1135 | ===================== |
| 1136 | |
| 1137 | Some classes may not be appropriate to inherit from. In C++11, classes can |
| 1138 | use the ``final`` specifier to ensure that a class cannot be inherited from. |
Henry Schreiner | d8c7ee0 | 2020-07-20 13:35:21 -0400 | [diff] [blame] | 1139 | The ``py::is_final`` attribute can be used to ensure that Python classes |
Dustin Spicuzza | 0dfffcf | 2020-04-05 02:34:00 -0400 | [diff] [blame] | 1140 | cannot inherit from a specified type. The underlying C++ type does not need |
| 1141 | to be declared final. |
| 1142 | |
| 1143 | .. code-block:: cpp |
| 1144 | |
| 1145 | class IsFinal final {}; |
| 1146 | |
| 1147 | py::class_<IsFinal>(m, "IsFinal", py::is_final()); |
| 1148 | |
| 1149 | When you try to inherit from such a class in Python, you will now get this |
| 1150 | error: |
| 1151 | |
| 1152 | .. code-block:: pycon |
| 1153 | |
| 1154 | >>> class PyFinalChild(IsFinal): |
| 1155 | ... pass |
| 1156 | TypeError: type 'IsFinal' is not an acceptable base type |
| 1157 | |
| 1158 | .. note:: This attribute is currently ignored on PyPy |
| 1159 | |
Henry Schreiner | a6887b6 | 2020-08-19 14:53:59 -0400 | [diff] [blame] | 1160 | .. versionadded:: 2.6 |
| 1161 | |
oremanj | fd9bc8f | 2018-04-13 20:13:10 -0400 | [diff] [blame] | 1162 | Custom automatic downcasters |
| 1163 | ============================ |
| 1164 | |
| 1165 | As explained in :ref:`inheritance`, pybind11 comes with built-in |
| 1166 | understanding of the dynamic type of polymorphic objects in C++; that |
| 1167 | is, returning a Pet to Python produces a Python object that knows it's |
| 1168 | wrapping a Dog, if Pet has virtual methods and pybind11 knows about |
| 1169 | Dog and this Pet is in fact a Dog. Sometimes, you might want to |
| 1170 | provide this automatic downcasting behavior when creating bindings for |
| 1171 | a class hierarchy that does not use standard C++ polymorphism, such as |
| 1172 | LLVM [#f4]_. As long as there's some way to determine at runtime |
| 1173 | whether a downcast is safe, you can proceed by specializing the |
| 1174 | ``pybind11::polymorphic_type_hook`` template: |
| 1175 | |
| 1176 | .. code-block:: cpp |
| 1177 | |
| 1178 | enum class PetKind { Cat, Dog, Zebra }; |
| 1179 | struct Pet { // Not polymorphic: has no virtual methods |
| 1180 | const PetKind kind; |
| 1181 | int age = 0; |
| 1182 | protected: |
| 1183 | Pet(PetKind _kind) : kind(_kind) {} |
| 1184 | }; |
| 1185 | struct Dog : Pet { |
| 1186 | Dog() : Pet(PetKind::Dog) {} |
| 1187 | std::string sound = "woof!"; |
| 1188 | std::string bark() const { return sound; } |
| 1189 | }; |
| 1190 | |
| 1191 | namespace pybind11 { |
| 1192 | template<> struct polymorphic_type_hook<Pet> { |
| 1193 | static const void *get(const Pet *src, const std::type_info*& type) { |
| 1194 | // note that src may be nullptr |
| 1195 | if (src && src->kind == PetKind::Dog) { |
| 1196 | type = &typeid(Dog); |
| 1197 | return static_cast<const Dog*>(src); |
| 1198 | } |
| 1199 | return src; |
| 1200 | } |
| 1201 | }; |
| 1202 | } // namespace pybind11 |
| 1203 | |
| 1204 | When pybind11 wants to convert a C++ pointer of type ``Base*`` to a |
| 1205 | Python object, it calls ``polymorphic_type_hook<Base>::get()`` to |
| 1206 | determine if a downcast is possible. The ``get()`` function should use |
| 1207 | whatever runtime information is available to determine if its ``src`` |
| 1208 | parameter is in fact an instance of some class ``Derived`` that |
| 1209 | inherits from ``Base``. If it finds such a ``Derived``, it sets ``type |
| 1210 | = &typeid(Derived)`` and returns a pointer to the ``Derived`` object |
| 1211 | that contains ``src``. Otherwise, it just returns ``src``, leaving |
| 1212 | ``type`` at its default value of nullptr. If you set ``type`` to a |
| 1213 | type that pybind11 doesn't know about, no downcasting will occur, and |
| 1214 | the original ``src`` pointer will be used with its static type |
| 1215 | ``Base*``. |
| 1216 | |
| 1217 | It is critical that the returned pointer and ``type`` argument of |
| 1218 | ``get()`` agree with each other: if ``type`` is set to something |
| 1219 | non-null, the returned pointer must point to the start of an object |
| 1220 | whose type is ``type``. If the hierarchy being exposed uses only |
| 1221 | single inheritance, a simple ``return src;`` will achieve this just |
| 1222 | fine, but in the general case, you must cast ``src`` to the |
| 1223 | appropriate derived-class pointer (e.g. using |
| 1224 | ``static_cast<Derived>(src)``) before allowing it to be returned as a |
| 1225 | ``void*``. |
| 1226 | |
| 1227 | .. [#f4] https://llvm.org/docs/HowToSetUpLLVMStyleRTTI.html |
| 1228 | |
| 1229 | .. note:: |
| 1230 | |
| 1231 | pybind11's standard support for downcasting objects whose types |
| 1232 | have virtual methods is implemented using |
| 1233 | ``polymorphic_type_hook`` too, using the standard C++ ability to |
| 1234 | determine the most-derived type of a polymorphic object using |
| 1235 | ``typeid()`` and to cast a base pointer to that most-derived type |
| 1236 | (even if you don't know what it is) using ``dynamic_cast<void*>``. |
| 1237 | |
| 1238 | .. seealso:: |
| 1239 | |
| 1240 | The file :file:`tests/test_tagbased_polymorphic.cpp` contains a |
| 1241 | more complete example, including a demonstration of how to provide |
| 1242 | automatic downcasting for an entire class hierarchy without |
| 1243 | writing one get() function for each class. |
Henry Schreiner | f12ec00 | 2020-09-14 18:06:26 -0400 | [diff] [blame] | 1244 | |
| 1245 | Accessing the type object |
| 1246 | ========================= |
| 1247 | |
| 1248 | You can get the type object from a C++ class that has already been registered using: |
| 1249 | |
| 1250 | .. code-block:: python |
| 1251 | |
| 1252 | py::type T_py = py::type::of<T>(); |
| 1253 | |
| 1254 | You can directly use ``py::type::of(ob)`` to get the type object from any python |
| 1255 | object, just like ``type(ob)`` in Python. |
| 1256 | |
| 1257 | .. note:: |
| 1258 | |
| 1259 | Other types, like ``py::type::of<int>()``, do not work, see :ref:`type-conversions`. |
| 1260 | |
| 1261 | .. versionadded:: 2.6 |