Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 1 | .. _advanced: |
| 2 | |
| 3 | Advanced topics |
| 4 | ############### |
| 5 | |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 6 | For brevity, the rest of this chapter assumes that the following two lines are |
| 7 | present: |
| 8 | |
| 9 | .. code-block:: cpp |
| 10 | |
Wenzel Jakob | 8f4eb00 | 2015-10-15 18:13:33 +0200 | [diff] [blame] | 11 | #include <pybind11/pybind11.h> |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 12 | |
Wenzel Jakob | 10e62e1 | 2015-10-15 22:46:07 +0200 | [diff] [blame] | 13 | namespace py = pybind11; |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 14 | |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 15 | Operator overloading |
| 16 | ==================== |
| 17 | |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 18 | Suppose that we're given the following ``Vector2`` class with a vector addition |
| 19 | and scalar multiplication operation, all implemented using overloaded operators |
| 20 | in C++. |
| 21 | |
| 22 | .. code-block:: cpp |
| 23 | |
| 24 | class Vector2 { |
| 25 | public: |
| 26 | Vector2(float x, float y) : x(x), y(y) { } |
| 27 | |
| 28 | std::string toString() const { return "[" + std::to_string(x) + ", " + std::to_string(y) + "]"; } |
| 29 | |
| 30 | Vector2 operator+(const Vector2 &v) const { return Vector2(x + v.x, y + v.y); } |
| 31 | Vector2 operator*(float value) const { return Vector2(x * value, y * value); } |
| 32 | Vector2& operator+=(const Vector2 &v) { x += v.x; y += v.y; return *this; } |
| 33 | Vector2& operator*=(float v) { x *= v; y *= v; return *this; } |
| 34 | |
| 35 | friend Vector2 operator*(float f, const Vector2 &v) { return Vector2(f * v.x, f * v.y); } |
| 36 | |
| 37 | private: |
| 38 | float x, y; |
| 39 | }; |
| 40 | |
| 41 | The following snippet shows how the above operators can be conveniently exposed |
| 42 | to Python. |
| 43 | |
| 44 | .. code-block:: cpp |
| 45 | |
Wenzel Jakob | 8f4eb00 | 2015-10-15 18:13:33 +0200 | [diff] [blame] | 46 | #include <pybind11/operators.h> |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 47 | |
Wenzel Jakob | b1b7140 | 2015-10-18 16:48:30 +0200 | [diff] [blame] | 48 | PYBIND11_PLUGIN(example) { |
Wenzel Jakob | 8f4eb00 | 2015-10-15 18:13:33 +0200 | [diff] [blame] | 49 | py::module m("example", "pybind11 example plugin"); |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 50 | |
| 51 | py::class_<Vector2>(m, "Vector2") |
| 52 | .def(py::init<float, float>()) |
| 53 | .def(py::self + py::self) |
| 54 | .def(py::self += py::self) |
| 55 | .def(py::self *= float()) |
| 56 | .def(float() * py::self) |
| 57 | .def("__repr__", &Vector2::toString); |
| 58 | |
| 59 | return m.ptr(); |
| 60 | } |
| 61 | |
| 62 | Note that a line like |
| 63 | |
| 64 | .. code-block:: cpp |
| 65 | |
| 66 | .def(py::self * float()) |
| 67 | |
| 68 | is really just short hand notation for |
| 69 | |
| 70 | .. code-block:: cpp |
| 71 | |
| 72 | .def("__mul__", [](const Vector2 &a, float b) { |
| 73 | return a * b; |
| 74 | }) |
| 75 | |
| 76 | This can be useful for exposing additional operators that don't exist on the |
| 77 | C++ side, or to perform other types of customization. |
| 78 | |
| 79 | .. note:: |
| 80 | |
| 81 | To use the more convenient ``py::self`` notation, the additional |
Wenzel Jakob | 8f4eb00 | 2015-10-15 18:13:33 +0200 | [diff] [blame] | 82 | header file :file:`pybind11/operators.h` must be included. |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 83 | |
| 84 | .. seealso:: |
| 85 | |
| 86 | The file :file:`example/example3.cpp` contains a complete example that |
| 87 | demonstrates how to work with overloaded operators in more detail. |
| 88 | |
| 89 | Callbacks and passing anonymous functions |
| 90 | ========================================= |
| 91 | |
| 92 | The C++11 standard brought lambda functions and the generic polymorphic |
| 93 | function wrapper ``std::function<>`` to the C++ programming language, which |
| 94 | enable powerful new ways of working with functions. Lambda functions come in |
| 95 | two flavors: stateless lambda function resemble classic function pointers that |
| 96 | link to an anonymous piece of code, while stateful lambda functions |
| 97 | additionally depend on captured variables that are stored in an anonymous |
| 98 | *lambda closure object*. |
| 99 | |
| 100 | Here is a simple example of a C++ function that takes an arbitrary function |
| 101 | (stateful or stateless) with signature ``int -> int`` as an argument and runs |
| 102 | it with the value 10. |
| 103 | |
| 104 | .. code-block:: cpp |
| 105 | |
| 106 | int func_arg(const std::function<int(int)> &f) { |
| 107 | return f(10); |
| 108 | } |
| 109 | |
| 110 | The example below is more involved: it takes a function of signature ``int -> int`` |
| 111 | and returns another function of the same kind. The return value is a stateful |
| 112 | lambda function, which stores the value ``f`` in the capture object and adds 1 to |
| 113 | its return value upon execution. |
| 114 | |
| 115 | .. code-block:: cpp |
| 116 | |
| 117 | std::function<int(int)> func_ret(const std::function<int(int)> &f) { |
| 118 | return [f](int i) { |
| 119 | return f(i) + 1; |
| 120 | }; |
| 121 | } |
| 122 | |
Wenzel Jakob | 8f4eb00 | 2015-10-15 18:13:33 +0200 | [diff] [blame] | 123 | After including the extra header file :file:`pybind11/functional.h`, it is almost |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 124 | trivial to generate binding code for both of these functions. |
| 125 | |
| 126 | .. code-block:: cpp |
| 127 | |
Wenzel Jakob | 8f4eb00 | 2015-10-15 18:13:33 +0200 | [diff] [blame] | 128 | #include <pybind11/functional.h> |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 129 | |
Wenzel Jakob | b1b7140 | 2015-10-18 16:48:30 +0200 | [diff] [blame] | 130 | PYBIND11_PLUGIN(example) { |
Wenzel Jakob | 8f4eb00 | 2015-10-15 18:13:33 +0200 | [diff] [blame] | 131 | py::module m("example", "pybind11 example plugin"); |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 132 | |
| 133 | m.def("func_arg", &func_arg); |
| 134 | m.def("func_ret", &func_ret); |
| 135 | |
| 136 | return m.ptr(); |
| 137 | } |
| 138 | |
| 139 | The following interactive session shows how to call them from Python. |
| 140 | |
| 141 | .. code-block:: python |
| 142 | |
| 143 | $ python |
| 144 | >>> import example |
| 145 | >>> def square(i): |
| 146 | ... return i * i |
| 147 | ... |
| 148 | >>> example.func_arg(square) |
| 149 | 100L |
| 150 | >>> square_plus_1 = example.func_ret(square) |
| 151 | >>> square_plus_1(4) |
| 152 | 17L |
| 153 | >>> |
| 154 | |
| 155 | .. note:: |
| 156 | |
| 157 | This functionality is very useful when generating bindings for callbacks in |
| 158 | C++ libraries (e.g. a graphical user interface library). |
| 159 | |
| 160 | The file :file:`example/example5.cpp` contains a complete example that |
| 161 | demonstrates how to work with callbacks and anonymous functions in more detail. |
| 162 | |
Wenzel Jakob | a4175d6 | 2015-11-17 08:30:34 +0100 | [diff] [blame] | 163 | .. warning:: |
| 164 | |
| 165 | Keep in mind that passing a function from C++ to Python (or vice versa) |
| 166 | will instantiate a piece of wrapper code that translates function |
| 167 | invocations between the two languages. Copying the same function back and |
| 168 | forth between Python and C++ many times in a row will cause these wrappers |
| 169 | to accumulate, which can decrease performance. |
| 170 | |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 171 | Overriding virtual functions in Python |
| 172 | ====================================== |
| 173 | |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 174 | Suppose that a C++ class or interface has a virtual function that we'd like to |
| 175 | to override from within Python (we'll focus on the class ``Animal``; ``Dog`` is |
| 176 | given as a specific example of how one would do this with traditional C++ |
| 177 | code). |
| 178 | |
| 179 | .. code-block:: cpp |
| 180 | |
| 181 | class Animal { |
| 182 | public: |
| 183 | virtual ~Animal() { } |
| 184 | virtual std::string go(int n_times) = 0; |
| 185 | }; |
| 186 | |
| 187 | class Dog : public Animal { |
| 188 | public: |
| 189 | std::string go(int n_times) { |
| 190 | std::string result; |
| 191 | for (int i=0; i<n_times; ++i) |
| 192 | result += "woof! "; |
| 193 | return result; |
| 194 | } |
| 195 | }; |
| 196 | |
| 197 | Let's also suppose that we are given a plain function which calls the |
| 198 | function ``go()`` on an arbitrary ``Animal`` instance. |
| 199 | |
| 200 | .. code-block:: cpp |
| 201 | |
| 202 | std::string call_go(Animal *animal) { |
| 203 | return animal->go(3); |
| 204 | } |
| 205 | |
| 206 | Normally, the binding code for these classes would look as follows: |
| 207 | |
| 208 | .. code-block:: cpp |
| 209 | |
Wenzel Jakob | b1b7140 | 2015-10-18 16:48:30 +0200 | [diff] [blame] | 210 | PYBIND11_PLUGIN(example) { |
Wenzel Jakob | 8f4eb00 | 2015-10-15 18:13:33 +0200 | [diff] [blame] | 211 | py::module m("example", "pybind11 example plugin"); |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 212 | |
| 213 | py::class_<Animal> animal(m, "Animal"); |
| 214 | animal |
| 215 | .def("go", &Animal::go); |
| 216 | |
| 217 | py::class_<Dog>(m, "Dog", animal) |
| 218 | .def(py::init<>()); |
| 219 | |
| 220 | m.def("call_go", &call_go); |
| 221 | |
| 222 | return m.ptr(); |
| 223 | } |
| 224 | |
| 225 | However, these bindings are impossible to extend: ``Animal`` is not |
| 226 | constructible, and we clearly require some kind of "trampoline" that |
| 227 | redirects virtual calls back to Python. |
| 228 | |
| 229 | Defining a new type of ``Animal`` from within Python is possible but requires a |
| 230 | helper class that is defined as follows: |
| 231 | |
| 232 | .. code-block:: cpp |
| 233 | |
| 234 | class PyAnimal : public Animal { |
| 235 | public: |
| 236 | /* Inherit the constructors */ |
| 237 | using Animal::Animal; |
| 238 | |
| 239 | /* Trampoline (need one for each virtual function) */ |
| 240 | std::string go(int n_times) { |
Wenzel Jakob | b1b7140 | 2015-10-18 16:48:30 +0200 | [diff] [blame] | 241 | PYBIND11_OVERLOAD_PURE( |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 242 | std::string, /* Return type */ |
| 243 | Animal, /* Parent class */ |
| 244 | go, /* Name of function */ |
| 245 | n_times /* Argument(s) */ |
| 246 | ); |
| 247 | } |
| 248 | }; |
| 249 | |
Wenzel Jakob | b1b7140 | 2015-10-18 16:48:30 +0200 | [diff] [blame] | 250 | The macro :func:`PYBIND11_OVERLOAD_PURE` should be used for pure virtual |
| 251 | functions, and :func:`PYBIND11_OVERLOAD` should be used for functions which have |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 252 | a default implementation. The binding code also needs a few minor adaptations |
| 253 | (highlighted): |
| 254 | |
| 255 | .. code-block:: cpp |
| 256 | :emphasize-lines: 4,6,7 |
| 257 | |
Wenzel Jakob | b1b7140 | 2015-10-18 16:48:30 +0200 | [diff] [blame] | 258 | PYBIND11_PLUGIN(example) { |
Wenzel Jakob | 8f4eb00 | 2015-10-15 18:13:33 +0200 | [diff] [blame] | 259 | py::module m("example", "pybind11 example plugin"); |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 260 | |
| 261 | py::class_<PyAnimal> animal(m, "Animal"); |
| 262 | animal |
| 263 | .alias<Animal>() |
| 264 | .def(py::init<>()) |
| 265 | .def("go", &Animal::go); |
| 266 | |
| 267 | py::class_<Dog>(m, "Dog", animal) |
| 268 | .def(py::init<>()); |
| 269 | |
| 270 | m.def("call_go", &call_go); |
| 271 | |
| 272 | return m.ptr(); |
| 273 | } |
| 274 | |
| 275 | Importantly, the trampoline helper class is used as the template argument to |
| 276 | :class:`class_`, and a call to :func:`class_::alias` informs the binding |
| 277 | generator that this is merely an alias for the underlying type ``Animal``. |
| 278 | Following this, we are able to define a constructor as usual. |
| 279 | |
| 280 | The Python session below shows how to override ``Animal::go`` and invoke it via |
| 281 | a virtual method call. |
| 282 | |
| 283 | .. code-block:: cpp |
| 284 | |
| 285 | >>> from example import * |
| 286 | >>> d = Dog() |
| 287 | >>> call_go(d) |
| 288 | u'woof! woof! woof! ' |
| 289 | >>> class Cat(Animal): |
| 290 | ... def go(self, n_times): |
| 291 | ... return "meow! " * n_times |
| 292 | ... |
| 293 | >>> c = Cat() |
| 294 | >>> call_go(c) |
| 295 | u'meow! meow! meow! ' |
| 296 | |
| 297 | .. seealso:: |
| 298 | |
| 299 | The file :file:`example/example12.cpp` contains a complete example that |
| 300 | demonstrates how to override virtual functions using pybind11 in more |
| 301 | detail. |
| 302 | |
Wenzel Jakob | ecdd868 | 2015-12-07 18:17:58 +0100 | [diff] [blame] | 303 | |
| 304 | Global Interpreter Lock (GIL) |
| 305 | ============================= |
| 306 | |
| 307 | The classes :class:`gil_scoped_release` and :class:`gil_scoped_acquire` can be |
| 308 | used to acquire and release the global interpreter lock in the body of a C++ |
| 309 | function call. In this way, long-running C++ code can be parallelized using |
| 310 | multiple Python threads. Taking the previous section as an example, this could |
| 311 | be realized as follows (important changes highlighted): |
| 312 | |
| 313 | .. code-block:: cpp |
| 314 | :emphasize-lines: 8,9,33,34 |
| 315 | |
| 316 | class PyAnimal : public Animal { |
| 317 | public: |
| 318 | /* Inherit the constructors */ |
| 319 | using Animal::Animal; |
| 320 | |
| 321 | /* Trampoline (need one for each virtual function) */ |
| 322 | std::string go(int n_times) { |
| 323 | /* Acquire GIL before calling Python code */ |
Wenzel Jakob | a4caa85 | 2015-12-14 12:39:02 +0100 | [diff] [blame] | 324 | py::gil_scoped_acquire acquire; |
Wenzel Jakob | ecdd868 | 2015-12-07 18:17:58 +0100 | [diff] [blame] | 325 | |
| 326 | PYBIND11_OVERLOAD_PURE( |
| 327 | std::string, /* Return type */ |
| 328 | Animal, /* Parent class */ |
| 329 | go, /* Name of function */ |
| 330 | n_times /* Argument(s) */ |
| 331 | ); |
| 332 | } |
| 333 | }; |
| 334 | |
| 335 | PYBIND11_PLUGIN(example) { |
| 336 | py::module m("example", "pybind11 example plugin"); |
| 337 | |
| 338 | py::class_<PyAnimal> animal(m, "Animal"); |
| 339 | animal |
| 340 | .alias<Animal>() |
| 341 | .def(py::init<>()) |
| 342 | .def("go", &Animal::go); |
| 343 | |
| 344 | py::class_<Dog>(m, "Dog", animal) |
| 345 | .def(py::init<>()); |
| 346 | |
| 347 | m.def("call_go", [](Animal *animal) -> std::string { |
| 348 | /* Release GIL before calling into (potentially long-running) C++ code */ |
Wenzel Jakob | a4caa85 | 2015-12-14 12:39:02 +0100 | [diff] [blame] | 349 | py::gil_scoped_release release; |
Wenzel Jakob | ecdd868 | 2015-12-07 18:17:58 +0100 | [diff] [blame] | 350 | return call_go(animal); |
| 351 | }); |
| 352 | |
| 353 | return m.ptr(); |
| 354 | } |
| 355 | |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 356 | Passing STL data structures |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 357 | =========================== |
| 358 | |
Wenzel Jakob | 8f4eb00 | 2015-10-15 18:13:33 +0200 | [diff] [blame] | 359 | When including the additional header file :file:`pybind11/stl.h`, conversions |
Jared Casper | 6be9e2f | 2015-12-15 15:56:14 -0800 | [diff] [blame] | 360 | between ``std::vector<>``, ``std::set<>``, and ``std::map<>`` and the Python |
Wenzel Jakob | 44db04f | 2015-12-14 12:40:45 +0100 | [diff] [blame] | 361 | ``list``, ``set`` and ``dict`` data structures are automatically enabled. The |
| 362 | types ``std::pair<>`` and ``std::tuple<>`` are already supported out of the box |
| 363 | with just the core :file:`pybind11/pybind11.h` header. |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 364 | |
| 365 | .. note:: |
| 366 | |
Wenzel Jakob | 44db04f | 2015-12-14 12:40:45 +0100 | [diff] [blame] | 367 | Arbitrary nesting of any of these types is supported. |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 368 | |
| 369 | .. seealso:: |
| 370 | |
| 371 | The file :file:`example/example2.cpp` contains a complete example that |
| 372 | demonstrates how to pass STL data types in more detail. |
| 373 | |
| 374 | Binding sequence data types, the slicing protocol, etc. |
| 375 | ======================================================= |
| 376 | |
| 377 | Please refer to the supplemental example for details. |
| 378 | |
| 379 | .. seealso:: |
| 380 | |
| 381 | The file :file:`example/example6.cpp` contains a complete example that |
| 382 | shows how to bind a sequence data type, including length queries |
| 383 | (``__len__``), iterators (``__iter__``), the slicing protocol and other |
| 384 | kinds of useful operations. |
| 385 | |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 386 | Return value policies |
| 387 | ===================== |
| 388 | |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 389 | Python and C++ use wildly different ways of managing the memory and lifetime of |
| 390 | objects managed by them. This can lead to issues when creating bindings for |
| 391 | functions that return a non-trivial type. Just by looking at the type |
| 392 | information, it is not clear whether Python should take charge of the returned |
| 393 | value and eventually free its resources, or if this is handled on the C++ side. |
| 394 | For this reason, pybind11 provides a several `return value policy` annotations |
| 395 | that can be passed to the :func:`module::def` and :func:`class_::def` |
Wenzel Jakob | 61d67f0 | 2015-12-14 12:53:06 +0100 | [diff] [blame] | 396 | functions. The default policy is :enum:`return_value_policy::automatic`. |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 397 | |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 398 | |
| 399 | +--------------------------------------------------+---------------------------------------------------------------------------+ |
| 400 | | Return value policy | Description | |
| 401 | +==================================================+===========================================================================+ |
| 402 | | :enum:`return_value_policy::automatic` | Automatic: copy objects returned as values and take ownership of | |
| 403 | | | objects returned as pointers | |
| 404 | +--------------------------------------------------+---------------------------------------------------------------------------+ |
| 405 | | :enum:`return_value_policy::copy` | Create a new copy of the returned object, which will be owned by Python | |
| 406 | +--------------------------------------------------+---------------------------------------------------------------------------+ |
| 407 | | :enum:`return_value_policy::take_ownership` | Reference the existing object and take ownership. Python will call | |
| 408 | | | the destructor and delete operator when the reference count reaches zero | |
| 409 | +--------------------------------------------------+---------------------------------------------------------------------------+ |
| 410 | | :enum:`return_value_policy::reference` | Reference the object, but do not take ownership and defer responsibility | |
| 411 | | | for deleting it to C++ (dangerous when C++ code at some point decides to | |
| 412 | | | delete it while Python still has a nonzero reference count) | |
| 413 | +--------------------------------------------------+---------------------------------------------------------------------------+ |
| 414 | | :enum:`return_value_policy::reference_internal` | Reference the object, but do not take ownership. The object is considered | |
| 415 | | | be owned by the C++ instance whose method or property returned it. The | |
| 416 | | | Python object will increase the reference count of this 'parent' by 1 | |
| 417 | | | to ensure that it won't be deallocated while Python is using the 'child' | |
| 418 | +--------------------------------------------------+---------------------------------------------------------------------------+ |
| 419 | |
| 420 | .. warning:: |
| 421 | |
| 422 | Code with invalid call policies might access unitialized memory and free |
| 423 | data structures multiple times, which can lead to hard-to-debug |
| 424 | non-determinism and segmentation faults, hence it is worth spending the |
| 425 | time to understand all the different options above. |
| 426 | |
| 427 | See below for an example that uses the |
| 428 | :enum:`return_value_policy::reference_internal` policy. |
| 429 | |
| 430 | .. code-block:: cpp |
| 431 | |
| 432 | class Example { |
| 433 | public: |
| 434 | Internal &get_internal() { return internal; } |
| 435 | private: |
| 436 | Internal internal; |
| 437 | }; |
| 438 | |
Wenzel Jakob | b1b7140 | 2015-10-18 16:48:30 +0200 | [diff] [blame] | 439 | PYBIND11_PLUGIN(example) { |
Wenzel Jakob | 8f4eb00 | 2015-10-15 18:13:33 +0200 | [diff] [blame] | 440 | py::module m("example", "pybind11 example plugin"); |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 441 | |
| 442 | py::class_<Example>(m, "Example") |
| 443 | .def(py::init<>()) |
| 444 | .def("get_internal", &Example::get_internal, "Return the internal data", py::return_value_policy::reference_internal) |
| 445 | |
| 446 | return m.ptr(); |
| 447 | } |
| 448 | |
Wenzel Jakob | 5f218b3 | 2016-01-17 22:36:39 +0100 | [diff] [blame] | 449 | |
| 450 | Additional call policies |
| 451 | ======================== |
| 452 | |
| 453 | In addition to the above return value policies, further `call policies` can be |
| 454 | specified to indicate dependencies between parameters. There is currently just |
| 455 | one policy named ``keep_alive<Nurse, Patient>``, which indicates that the |
| 456 | argument with index ``Patient`` should be kept alive at least until the |
| 457 | argument with index ``Nurse`` is freed by the garbage collector; argument |
| 458 | indices start at one, while zero refers to the return value. Arbitrarily many |
| 459 | call policies can be specified. |
| 460 | |
| 461 | For instance, binding code for a a list append operation that ties the lifetime |
| 462 | of the newly added element to the underlying container might be declared as |
| 463 | follows: |
| 464 | |
| 465 | .. code-block:: cpp |
| 466 | |
| 467 | py::class_<List>(m, "List") |
| 468 | .def("append", &List::append, py::keep_alive<1, 2>()); |
| 469 | |
| 470 | .. note:: |
| 471 | |
| 472 | ``keep_alive`` is analogous to the ``with_custodian_and_ward`` (if Nurse, |
| 473 | Patient != 0) and ``with_custodian_and_ward_postcall`` (if Nurse/Patient == |
| 474 | 0) policies from Boost.Python. |
| 475 | |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 476 | Implicit type conversions |
| 477 | ========================= |
| 478 | |
| 479 | Suppose that instances of two types ``A`` and ``B`` are used in a project, and |
| 480 | that an ``A`` can easily be converted into a an instance of type ``B`` (examples of this |
| 481 | could be a fixed and an arbitrary precision number type). |
| 482 | |
| 483 | .. code-block:: cpp |
| 484 | |
| 485 | py::class_<A>(m, "A") |
| 486 | /// ... members ... |
| 487 | |
| 488 | py::class_<B>(m, "B") |
| 489 | .def(py::init<A>()) |
| 490 | /// ... members ... |
| 491 | |
| 492 | m.def("func", |
| 493 | [](const B &) { /* .... */ } |
| 494 | ); |
| 495 | |
| 496 | To invoke the function ``func`` using a variable ``a`` containing an ``A`` |
| 497 | instance, we'd have to write ``func(B(a))`` in Python. On the other hand, C++ |
| 498 | will automatically apply an implicit type conversion, which makes it possible |
| 499 | to directly write ``func(a)``. |
| 500 | |
| 501 | In this situation (i.e. where ``B`` has a constructor that converts from |
| 502 | ``A``), the following statement enables similar implicit conversions on the |
| 503 | Python side: |
| 504 | |
| 505 | .. code-block:: cpp |
| 506 | |
| 507 | py::implicitly_convertible<A, B>(); |
| 508 | |
| 509 | Smart pointers |
| 510 | ============== |
| 511 | |
| 512 | The binding generator for classes (:class:`class_`) takes an optional second |
| 513 | template type, which denotes a special *holder* type that is used to manage |
| 514 | references to the object. When wrapping a type named ``Type``, the default |
| 515 | value of this template parameter is ``std::unique_ptr<Type>``, which means that |
| 516 | the object is deallocated when Python's reference count goes to zero. |
| 517 | |
Wenzel Jakob | 1853b65 | 2015-10-18 15:38:50 +0200 | [diff] [blame] | 518 | It is possible to switch to other types of reference counting wrappers or smart |
| 519 | pointers, which is useful in codebases that rely on them. For instance, the |
| 520 | following snippet causes ``std::shared_ptr`` to be used instead. |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 521 | |
| 522 | .. code-block:: cpp |
| 523 | |
Wenzel Jakob | b2c2c79 | 2016-01-17 22:36:40 +0100 | [diff] [blame] | 524 | py::class_<Example, std::shared_ptr<Example> /* <- holder type */> obj(m, "Example"); |
Wenzel Jakob | 5ef1219 | 2015-12-15 17:07:35 +0100 | [diff] [blame] | 525 | |
Wenzel Jakob | b2c2c79 | 2016-01-17 22:36:40 +0100 | [diff] [blame] | 526 | Note that any particular class can only be associated with a single holder type. |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 527 | |
Wenzel Jakob | 1853b65 | 2015-10-18 15:38:50 +0200 | [diff] [blame] | 528 | To enable transparent conversions for functions that take shared pointers as an |
Wenzel Jakob | 5ef1219 | 2015-12-15 17:07:35 +0100 | [diff] [blame] | 529 | argument or that return them, a macro invocation similar to the following must |
Wenzel Jakob | 1853b65 | 2015-10-18 15:38:50 +0200 | [diff] [blame] | 530 | be declared at the top level before any binding code: |
| 531 | |
| 532 | .. code-block:: cpp |
| 533 | |
Wenzel Jakob | b1b7140 | 2015-10-18 16:48:30 +0200 | [diff] [blame] | 534 | PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>); |
Wenzel Jakob | 1853b65 | 2015-10-18 15:38:50 +0200 | [diff] [blame] | 535 | |
Wenzel Jakob | b2c2c79 | 2016-01-17 22:36:40 +0100 | [diff] [blame] | 536 | .. note:: |
Wenzel Jakob | 61d67f0 | 2015-12-14 12:53:06 +0100 | [diff] [blame] | 537 | |
| 538 | The first argument of :func:`PYBIND11_DECLARE_HOLDER_TYPE` should be a |
| 539 | placeholder name that is used as a template parameter of the second |
| 540 | argument. Thus, feel free to use any identifier, but use it consistently on |
| 541 | both sides; also, don't use the name of a type that already exists in your |
| 542 | codebase. |
| 543 | |
Wenzel Jakob | b2c2c79 | 2016-01-17 22:36:40 +0100 | [diff] [blame] | 544 | One potential stumbling block when using holder types is that they need to be |
| 545 | applied consistently. Can you guess what's broken about the following binding |
| 546 | code? |
Wenzel Jakob | 6e213c9 | 2015-11-24 23:05:58 +0100 | [diff] [blame] | 547 | |
Wenzel Jakob | b2c2c79 | 2016-01-17 22:36:40 +0100 | [diff] [blame] | 548 | .. code-block:: cpp |
Wenzel Jakob | 6e213c9 | 2015-11-24 23:05:58 +0100 | [diff] [blame] | 549 | |
Wenzel Jakob | b2c2c79 | 2016-01-17 22:36:40 +0100 | [diff] [blame] | 550 | class Child { }; |
Wenzel Jakob | 5ef1219 | 2015-12-15 17:07:35 +0100 | [diff] [blame] | 551 | |
Wenzel Jakob | b2c2c79 | 2016-01-17 22:36:40 +0100 | [diff] [blame] | 552 | class Parent { |
| 553 | public: |
| 554 | Parent() : child(std::make_shared<Child>()) { } |
| 555 | Child *get_child() { return child.get(); } /* Hint: ** DON'T DO THIS ** */ |
| 556 | private: |
| 557 | std::shared_ptr<Child> child; |
| 558 | }; |
Wenzel Jakob | 5ef1219 | 2015-12-15 17:07:35 +0100 | [diff] [blame] | 559 | |
Wenzel Jakob | b2c2c79 | 2016-01-17 22:36:40 +0100 | [diff] [blame] | 560 | PYBIND11_PLUGIN(example) { |
| 561 | py::module m("example"); |
Wenzel Jakob | 5ef1219 | 2015-12-15 17:07:35 +0100 | [diff] [blame] | 562 | |
Wenzel Jakob | b2c2c79 | 2016-01-17 22:36:40 +0100 | [diff] [blame] | 563 | py::class_<Child, std::shared_ptr<Child>>(m, "Child"); |
| 564 | |
| 565 | py::class_<Parent, std::shared_ptr<Parent>>(m, "Parent") |
| 566 | .def(py::init<>()) |
| 567 | .def("get_child", &Parent::get_child); |
| 568 | |
| 569 | return m.ptr(); |
| 570 | } |
| 571 | |
| 572 | The following Python code will cause undefined behavior (and likely a |
| 573 | segmentation fault). |
| 574 | |
| 575 | .. code-block:: python |
| 576 | |
| 577 | from example import Parent |
| 578 | print(Parent().get_child()) |
| 579 | |
| 580 | The problem is that ``Parent::get_child()`` returns a pointer to an instance of |
| 581 | ``Child``, but the fact that this instance is already managed by |
| 582 | ``std::shared_ptr<...>`` is lost when passing raw pointers. In this case, |
| 583 | pybind11 will create a second independent ``std::shared_ptr<...>`` that also |
| 584 | claims ownership of the pointer. In the end, the object will be freed **twice** |
| 585 | since these shared pointers have no way of knowing about each other. |
| 586 | |
| 587 | There are two ways to resolve this issue: |
| 588 | |
| 589 | 1. For types that are managed by a smart pointer class, never use raw pointers |
| 590 | in function arguments or return values. In other words: always consistently |
| 591 | wrap pointers into their designated holder types (such as |
| 592 | ``std::shared_ptr<...>``). In this case, the signature of ``get_child()`` |
| 593 | should be modified as follows: |
| 594 | |
| 595 | .. code-block:: cpp |
| 596 | |
| 597 | std::shared_ptr<Child> get_child() { return child; } |
| 598 | |
| 599 | 2. Adjust the definition of ``Child`` by specifying |
| 600 | ``std::enable_shared_from_this<T>`` (see cppreference_ for details) as a |
| 601 | base class. This adds a small bit of information to ``Child`` that allows |
| 602 | pybind11 to realize that there is already an existing |
| 603 | ``std::shared_ptr<...>`` and communicate with it. In this case, the |
| 604 | declaration of ``Child`` should look as follows: |
Wenzel Jakob | 5ef1219 | 2015-12-15 17:07:35 +0100 | [diff] [blame] | 605 | |
Wenzel Jakob | 6e213c9 | 2015-11-24 23:05:58 +0100 | [diff] [blame] | 606 | .. _cppreference: http://en.cppreference.com/w/cpp/memory/enable_shared_from_this |
| 607 | |
Wenzel Jakob | b2c2c79 | 2016-01-17 22:36:40 +0100 | [diff] [blame] | 608 | .. code-block:: cpp |
| 609 | |
| 610 | class Child : public std::enable_shared_from_this<Child> { }; |
| 611 | |
Wenzel Jakob | 5ef1219 | 2015-12-15 17:07:35 +0100 | [diff] [blame] | 612 | .. seealso:: |
| 613 | |
| 614 | The file :file:`example/example8.cpp` contains a complete example that |
| 615 | demonstrates how to work with custom reference-counting holder types in |
| 616 | more detail. |
| 617 | |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 618 | .. _custom_constructors: |
| 619 | |
| 620 | Custom constructors |
| 621 | =================== |
| 622 | |
| 623 | The syntax for binding constructors was previously introduced, but it only |
| 624 | works when a constructor with the given parameters actually exists on the C++ |
| 625 | side. To extend this to more general cases, let's take a look at what actually |
| 626 | happens under the hood: the following statement |
| 627 | |
| 628 | .. code-block:: cpp |
| 629 | |
| 630 | py::class_<Example>(m, "Example") |
| 631 | .def(py::init<int>()); |
| 632 | |
| 633 | is short hand notation for |
| 634 | |
| 635 | .. code-block:: cpp |
| 636 | |
| 637 | py::class_<Example>(m, "Example") |
| 638 | .def("__init__", |
| 639 | [](Example &instance, int arg) { |
| 640 | new (&instance) Example(arg); |
| 641 | } |
| 642 | ); |
| 643 | |
| 644 | In other words, :func:`init` creates an anonymous function that invokes an |
| 645 | in-place constructor. Memory allocation etc. is already take care of beforehand |
| 646 | within pybind11. |
| 647 | |
| 648 | Catching and throwing exceptions |
| 649 | ================================ |
| 650 | |
| 651 | When C++ code invoked from Python throws an ``std::exception``, it is |
| 652 | automatically converted into a Python ``Exception``. pybind11 defines multiple |
| 653 | special exception classes that will map to different types of Python |
| 654 | exceptions: |
| 655 | |
| 656 | +----------------------------+------------------------------+ |
| 657 | | C++ exception type | Python exception type | |
| 658 | +============================+==============================+ |
| 659 | | :class:`std::exception` | ``Exception`` | |
| 660 | +----------------------------+------------------------------+ |
| 661 | | :class:`stop_iteration` | ``StopIteration`` (used to | |
| 662 | | | implement custom iterators) | |
| 663 | +----------------------------+------------------------------+ |
| 664 | | :class:`index_error` | ``IndexError`` (used to | |
| 665 | | | indicate out of bounds | |
| 666 | | | accesses in ``__getitem__``, | |
| 667 | | | ``__setitem__``, etc.) | |
| 668 | +----------------------------+------------------------------+ |
| 669 | | :class:`error_already_set` | Indicates that the Python | |
| 670 | | | exception flag has already | |
| 671 | | | been initialized. | |
| 672 | +----------------------------+------------------------------+ |
| 673 | |
| 674 | When a Python function invoked from C++ throws an exception, it is converted |
| 675 | into a C++ exception of type :class:`error_already_set` whose string payload |
| 676 | contains a textual summary. |
| 677 | |
| 678 | There is also a special exception :class:`cast_error` that is thrown by |
| 679 | :func:`handle::call` when the input arguments cannot be converted to Python |
| 680 | objects. |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 681 | |
| 682 | Buffer protocol |
| 683 | =============== |
| 684 | |
| 685 | Python supports an extremely general and convenient approach for exchanging |
| 686 | data between plugin libraries. Types can expose a buffer view which provides |
| 687 | fast direct access to the raw internal representation. Suppose we want to bind |
| 688 | the following simplistic Matrix class: |
| 689 | |
| 690 | .. code-block:: cpp |
| 691 | |
| 692 | class Matrix { |
| 693 | public: |
| 694 | Matrix(size_t rows, size_t cols) : m_rows(rows), m_cols(cols) { |
| 695 | m_data = new float[rows*cols]; |
| 696 | } |
| 697 | float *data() { return m_data; } |
| 698 | size_t rows() const { return m_rows; } |
| 699 | size_t cols() const { return m_cols; } |
| 700 | private: |
| 701 | size_t m_rows, m_cols; |
| 702 | float *m_data; |
| 703 | }; |
| 704 | |
| 705 | The following binding code exposes the ``Matrix`` contents as a buffer object, |
| 706 | making it possible to cast Matrixes into NumPy arrays. It is even possible to |
| 707 | completely avoid copy operations with Python expressions like |
| 708 | ``np.array(matrix_instance, copy = False)``. |
| 709 | |
| 710 | .. code-block:: cpp |
| 711 | |
| 712 | py::class_<Matrix>(m, "Matrix") |
| 713 | .def_buffer([](Matrix &m) -> py::buffer_info { |
| 714 | return py::buffer_info( |
| 715 | m.data(), /* Pointer to buffer */ |
| 716 | sizeof(float), /* Size of one scalar */ |
| 717 | py::format_descriptor<float>::value(), /* Python struct-style format descriptor */ |
| 718 | 2, /* Number of dimensions */ |
| 719 | { m.rows(), m.cols() }, /* Buffer dimensions */ |
| 720 | { sizeof(float) * m.rows(), /* Strides (in bytes) for each index */ |
| 721 | sizeof(float) } |
| 722 | ); |
| 723 | }); |
| 724 | |
| 725 | The snippet above binds a lambda function, which can create ``py::buffer_info`` |
| 726 | description records on demand describing a given matrix. The contents of |
| 727 | ``py::buffer_info`` mirror the Python buffer protocol specification. |
| 728 | |
| 729 | .. code-block:: cpp |
| 730 | |
| 731 | struct buffer_info { |
| 732 | void *ptr; |
| 733 | size_t itemsize; |
| 734 | std::string format; |
| 735 | int ndim; |
| 736 | std::vector<size_t> shape; |
| 737 | std::vector<size_t> strides; |
| 738 | }; |
| 739 | |
| 740 | To create a C++ function that can take a Python buffer object as an argument, |
| 741 | simply use the type ``py::buffer`` as one of its arguments. Buffers can exist |
| 742 | in a great variety of configurations, hence some safety checks are usually |
| 743 | necessary in the function body. Below, you can see an basic example on how to |
| 744 | define a custom constructor for the Eigen double precision matrix |
| 745 | (``Eigen::MatrixXd``) type, which supports initialization from compatible |
| 746 | buffer |
| 747 | objects (e.g. a NumPy matrix). |
| 748 | |
| 749 | .. code-block:: cpp |
| 750 | |
| 751 | py::class_<Eigen::MatrixXd>(m, "MatrixXd") |
| 752 | .def("__init__", [](Eigen::MatrixXd &m, py::buffer b) { |
| 753 | /* Request a buffer descriptor from Python */ |
| 754 | py::buffer_info info = b.request(); |
| 755 | |
| 756 | /* Some sanity checks ... */ |
| 757 | if (info.format != py::format_descriptor<double>::value()) |
| 758 | throw std::runtime_error("Incompatible format: expected a double array!"); |
| 759 | |
| 760 | if (info.ndim != 2) |
| 761 | throw std::runtime_error("Incompatible buffer dimension!"); |
| 762 | |
| 763 | if (info.strides[0] == sizeof(double)) { |
| 764 | /* Buffer has the right layout -- directly copy. */ |
| 765 | new (&m) Eigen::MatrixXd(info.shape[0], info.shape[1]); |
| 766 | memcpy(m.data(), info.ptr, sizeof(double) * m.size()); |
| 767 | } else { |
| 768 | /* Oops -- the buffer is transposed */ |
| 769 | new (&m) Eigen::MatrixXd(info.shape[1], info.shape[0]); |
| 770 | memcpy(m.data(), info.ptr, sizeof(double) * m.size()); |
| 771 | m.transposeInPlace(); |
| 772 | } |
| 773 | }); |
| 774 | |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 775 | .. seealso:: |
| 776 | |
| 777 | The file :file:`example/example7.cpp` contains a complete example that |
| 778 | demonstrates using the buffer protocol with pybind11 in more detail. |
| 779 | |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 780 | NumPy support |
| 781 | ============= |
| 782 | |
| 783 | By exchanging ``py::buffer`` with ``py::array`` in the above snippet, we can |
| 784 | restrict the function so that it only accepts NumPy arrays (rather than any |
| 785 | type of Python object satisfying the buffer object protocol). |
| 786 | |
| 787 | In many situations, we want to define a function which only accepts a NumPy |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 788 | array of a certain data type. This is possible via the ``py::array_t<T>`` |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 789 | template. For instance, the following function requires the argument to be a |
| 790 | dense array of doubles in C-style ordering. |
| 791 | |
| 792 | .. code-block:: cpp |
| 793 | |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 794 | void f(py::array_t<double> array); |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 795 | |
| 796 | When it is invoked with a different type (e.g. an integer), the binding code |
| 797 | will attempt to cast the input into a NumPy array of the requested type. |
Wenzel Jakob | 8f4eb00 | 2015-10-15 18:13:33 +0200 | [diff] [blame] | 798 | Note that this feature requires the ``pybind11/numpy.h`` header to be included. |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 799 | |
| 800 | Vectorizing functions |
| 801 | ===================== |
| 802 | |
| 803 | Suppose we want to bind a function with the following signature to Python so |
| 804 | that it can process arbitrary NumPy array arguments (vectors, matrices, general |
| 805 | N-D arrays) in addition to its normal arguments: |
| 806 | |
| 807 | .. code-block:: cpp |
| 808 | |
| 809 | double my_func(int x, float y, double z); |
| 810 | |
Wenzel Jakob | 8f4eb00 | 2015-10-15 18:13:33 +0200 | [diff] [blame] | 811 | After including the ``pybind11/numpy.h`` header, this is extremely simple: |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 812 | |
| 813 | .. code-block:: cpp |
| 814 | |
| 815 | m.def("vectorized_func", py::vectorize(my_func)); |
| 816 | |
| 817 | Invoking the function like below causes 4 calls to be made to ``my_func`` with |
| 818 | each of the the array elements. The result is returned as a NumPy array of type |
| 819 | ``numpy.dtype.float64``. |
| 820 | |
| 821 | .. code-block:: python |
| 822 | |
| 823 | >>> x = np.array([[1, 3],[5, 7]]) |
| 824 | >>> y = np.array([[2, 4],[6, 8]]) |
| 825 | >>> z = 3 |
| 826 | >>> result = vectorized_func(x, y, z) |
| 827 | |
| 828 | The scalar argument ``z`` is transparently replicated 4 times. The input |
| 829 | arrays ``x`` and ``y`` are automatically converted into the right types (they |
| 830 | are of type ``numpy.dtype.int64`` but need to be ``numpy.dtype.int32`` and |
| 831 | ``numpy.dtype.float32``, respectively) |
| 832 | |
| 833 | Sometimes we might want to explitly exclude an argument from the vectorization |
| 834 | because it makes little sense to wrap it in a NumPy array. For instance, |
| 835 | suppose the function signature was |
| 836 | |
| 837 | .. code-block:: cpp |
| 838 | |
| 839 | double my_func(int x, float y, my_custom_type *z); |
| 840 | |
| 841 | This can be done with a stateful Lambda closure: |
| 842 | |
| 843 | .. code-block:: cpp |
| 844 | |
| 845 | // Vectorize a lambda function with a capture object (e.g. to exclude some arguments from the vectorization) |
| 846 | m.def("vectorized_func", |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 847 | [](py::array_t<int> x, py::array_t<float> y, my_custom_type *z) { |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 848 | auto stateful_closure = [z](int x, float y) { return my_func(x, y, z); }; |
| 849 | return py::vectorize(stateful_closure)(x, y); |
| 850 | } |
| 851 | ); |
| 852 | |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 853 | .. seealso:: |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 854 | |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 855 | The file :file:`example/example10.cpp` contains a complete example that |
| 856 | demonstrates using :func:`vectorize` in more detail. |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 857 | |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 858 | Functions taking Python objects as arguments |
| 859 | ============================================ |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 860 | |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 861 | pybind11 exposes all major Python types using thin C++ wrapper classes. These |
| 862 | wrapper classes can also be used as parameters of functions in bindings, which |
| 863 | makes it possible to directly work with native Python types on the C++ side. |
| 864 | For instance, the following statement iterates over a Python ``dict``: |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 865 | |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 866 | .. code-block:: cpp |
| 867 | |
| 868 | void print_dict(py::dict dict) { |
| 869 | /* Easily interact with Python types */ |
| 870 | for (auto item : dict) |
| 871 | std::cout << "key=" << item.first << ", " |
| 872 | << "value=" << item.second << std::endl; |
| 873 | } |
| 874 | |
| 875 | Available types include :class:`handle`, :class:`object`, :class:`bool_`, |
Wenzel Jakob | 27e8e10 | 2016-01-17 22:36:37 +0100 | [diff] [blame] | 876 | :class:`int_`, :class:`float_`, :class:`str`, :class:`bytes`, :class:`tuple`, |
| 877 | :class:`list`, :class:`dict`, :class:`slice`, :class:`capsule`, |
| 878 | :class:`function`, :class:`buffer`, :class:`array`, and :class:`array_t`. |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 879 | |
Wenzel Jakob | 436b731 | 2015-10-20 01:04:30 +0200 | [diff] [blame] | 880 | In this kind of mixed code, it is often necessary to convert arbitrary C++ |
| 881 | types to Python, which can be done using :func:`cast`: |
| 882 | |
| 883 | .. code-block:: cpp |
| 884 | |
| 885 | MyClass *cls = ..; |
| 886 | py::object obj = py::cast(cls); |
| 887 | |
| 888 | The reverse direction uses the following syntax: |
| 889 | |
| 890 | .. code-block:: cpp |
| 891 | |
| 892 | py::object obj = ...; |
| 893 | MyClass *cls = obj.cast<MyClass *>(); |
| 894 | |
| 895 | When conversion fails, both directions throw the exception :class:`cast_error`. |
| 896 | |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 897 | .. seealso:: |
| 898 | |
| 899 | The file :file:`example/example2.cpp` contains a complete example that |
| 900 | demonstrates passing native Python types in more detail. |
Wenzel Jakob | 2ac5044 | 2016-01-17 22:36:35 +0100 | [diff] [blame] | 901 | |
| 902 | Default arguments revisited |
| 903 | =========================== |
| 904 | |
| 905 | The section on :ref:`default_args` previously discussed basic usage of default |
| 906 | arguments using pybind11. One noteworthy aspect of their implementation is that |
| 907 | default arguments are converted to Python objects right at declaration time. |
| 908 | Consider the following example: |
| 909 | |
| 910 | .. code-block:: cpp |
| 911 | |
| 912 | py::class_<MyClass>("MyClass") |
| 913 | .def("myFunction", py::arg("arg") = SomeType(123)); |
| 914 | |
| 915 | In this case, pybind11 must already be set up to deal with values of the type |
| 916 | ``SomeType`` (via a prior instantiation of ``py::class_<SomeType>``), or an |
| 917 | exception will be thrown. |
| 918 | |
| 919 | Another aspect worth highlighting is that the "preview" of the default argument |
| 920 | in the function signature is generated using the object's ``__repr__`` method. |
| 921 | If not available, the signature may not be very helpful, e.g.: |
| 922 | |
| 923 | .. code-block:: python |
| 924 | |
| 925 | FUNCTIONS |
| 926 | ... |
| 927 | | myFunction(...) |
Wenzel Jakob | 48548ea | 2016-01-17 22:36:44 +0100 | [diff] [blame^] | 928 | | Signature : (MyClass, arg : SomeType = <SomeType object at 0x101b7b080>) -> NoneType |
Wenzel Jakob | 2ac5044 | 2016-01-17 22:36:35 +0100 | [diff] [blame] | 929 | ... |
| 930 | |
| 931 | The first way of addressing this is by defining ``SomeType.__repr__``. |
| 932 | Alternatively, it is possible to specify the human-readable preview of the |
| 933 | default argument manually using the ``arg_t`` notation: |
| 934 | |
| 935 | .. code-block:: cpp |
| 936 | |
| 937 | py::class_<MyClass>("MyClass") |
| 938 | .def("myFunction", py::arg_t<SomeType>("arg", SomeType(123), "SomeType(123)")); |
| 939 | |
Wenzel Jakob | 2dfbade | 2016-01-17 22:36:37 +0100 | [diff] [blame] | 940 | Partitioning code over multiple extension modules |
| 941 | ================================================= |
| 942 | |
| 943 | It's straightforward to split binding code over multiple extension modules and |
| 944 | reference types declared elsewhere. Everything "just" works without any special |
| 945 | precautions. One exception to this rule occurs when wanting to extend a type declared |
| 946 | in another extension module. Recall the basic example from Section |
| 947 | :ref:`inheritance`. |
| 948 | |
| 949 | .. code-block:: cpp |
| 950 | |
| 951 | py::class_<Pet> pet(m, "Pet"); |
| 952 | pet.def(py::init<const std::string &>()) |
| 953 | .def_readwrite("name", &Pet::name); |
| 954 | |
| 955 | py::class_<Dog>(m, "Dog", pet /* <- specify parent */) |
| 956 | .def(py::init<const std::string &>()) |
| 957 | .def("bark", &Dog::bark); |
| 958 | |
| 959 | Suppose now that ``Pet`` bindings are defined in a module named ``basic``, |
| 960 | whereas the ``Dog`` bindings are defined somewhere else. The challenge is of |
| 961 | course that the variable ``pet`` is not available anymore though it is needed |
| 962 | to indicate the inheritance relationship to the constructor of ``class_<Dog>``. |
| 963 | However, it can be acquired as follows: |
| 964 | |
| 965 | .. code-block:: cpp |
| 966 | |
| 967 | py::object pet = (py::object) py::module::import("basic").attr("Pet"); |
| 968 | |
| 969 | py::class_<Dog>(m, "Dog", pet) |
| 970 | .def(py::init<const std::string &>()) |
| 971 | .def("bark", &Dog::bark); |
| 972 | |