blob: cc44ab142ce1fb9f782bbcc261b80e76b613ada6 [file] [log] [blame]
Wenzel Jakob28f98aa2015-10-13 02:57:16 +02001.. _advanced:
2
3Advanced topics
4###############
5
Wenzel Jakob93296692015-10-13 23:21:54 +02006For brevity, the rest of this chapter assumes that the following two lines are
7present:
8
9.. code-block:: cpp
10
Wenzel Jakob8f4eb002015-10-15 18:13:33 +020011 #include <pybind11/pybind11.h>
Wenzel Jakob93296692015-10-13 23:21:54 +020012
Wenzel Jakob10e62e12015-10-15 22:46:07 +020013 namespace py = pybind11;
Wenzel Jakob93296692015-10-13 23:21:54 +020014
Wenzel Jakobde3ad072016-02-02 11:38:21 +010015Exporting constants and mutable objects
16=======================================
17
18To expose a C++ constant, use the ``attr`` function to register it in a module
19as shown below. The ``int_`` class is one of many small wrapper objects defined
20in ``pybind11/pytypes.h``. General objects (including integers) can also be
21converted using the function ``cast``.
22
23.. code-block:: cpp
24
25 PYBIND11_PLUGIN(example) {
26 py::module m("example", "pybind11 example plugin");
27 m.attr("MY_CONSTANT") = py::int_(123);
28 m.attr("MY_CONSTANT_2") = py::cast(new MyObject());
29 }
30
Wenzel Jakob28f98aa2015-10-13 02:57:16 +020031Operator overloading
32====================
33
Wenzel Jakob93296692015-10-13 23:21:54 +020034Suppose that we're given the following ``Vector2`` class with a vector addition
35and scalar multiplication operation, all implemented using overloaded operators
36in C++.
37
38.. code-block:: cpp
39
40 class Vector2 {
41 public:
42 Vector2(float x, float y) : x(x), y(y) { }
43
44 std::string toString() const { return "[" + std::to_string(x) + ", " + std::to_string(y) + "]"; }
45
46 Vector2 operator+(const Vector2 &v) const { return Vector2(x + v.x, y + v.y); }
47 Vector2 operator*(float value) const { return Vector2(x * value, y * value); }
48 Vector2& operator+=(const Vector2 &v) { x += v.x; y += v.y; return *this; }
49 Vector2& operator*=(float v) { x *= v; y *= v; return *this; }
50
51 friend Vector2 operator*(float f, const Vector2 &v) { return Vector2(f * v.x, f * v.y); }
52
53 private:
54 float x, y;
55 };
56
57The following snippet shows how the above operators can be conveniently exposed
58to Python.
59
60.. code-block:: cpp
61
Wenzel Jakob8f4eb002015-10-15 18:13:33 +020062 #include <pybind11/operators.h>
Wenzel Jakob93296692015-10-13 23:21:54 +020063
Wenzel Jakobb1b71402015-10-18 16:48:30 +020064 PYBIND11_PLUGIN(example) {
Wenzel Jakob8f4eb002015-10-15 18:13:33 +020065 py::module m("example", "pybind11 example plugin");
Wenzel Jakob93296692015-10-13 23:21:54 +020066
67 py::class_<Vector2>(m, "Vector2")
68 .def(py::init<float, float>())
69 .def(py::self + py::self)
70 .def(py::self += py::self)
71 .def(py::self *= float())
72 .def(float() * py::self)
73 .def("__repr__", &Vector2::toString);
74
75 return m.ptr();
76 }
77
78Note that a line like
79
80.. code-block:: cpp
81
82 .def(py::self * float())
83
84is really just short hand notation for
85
86.. code-block:: cpp
87
88 .def("__mul__", [](const Vector2 &a, float b) {
89 return a * b;
90 })
91
92This can be useful for exposing additional operators that don't exist on the
93C++ side, or to perform other types of customization.
94
95.. note::
96
97 To use the more convenient ``py::self`` notation, the additional
Wenzel Jakob8f4eb002015-10-15 18:13:33 +020098 header file :file:`pybind11/operators.h` must be included.
Wenzel Jakob93296692015-10-13 23:21:54 +020099
100.. seealso::
101
102 The file :file:`example/example3.cpp` contains a complete example that
103 demonstrates how to work with overloaded operators in more detail.
104
105Callbacks and passing anonymous functions
106=========================================
107
108The C++11 standard brought lambda functions and the generic polymorphic
109function wrapper ``std::function<>`` to the C++ programming language, which
110enable powerful new ways of working with functions. Lambda functions come in
111two flavors: stateless lambda function resemble classic function pointers that
112link to an anonymous piece of code, while stateful lambda functions
113additionally depend on captured variables that are stored in an anonymous
114*lambda closure object*.
115
116Here is a simple example of a C++ function that takes an arbitrary function
117(stateful or stateless) with signature ``int -> int`` as an argument and runs
118it with the value 10.
119
120.. code-block:: cpp
121
122 int func_arg(const std::function<int(int)> &f) {
123 return f(10);
124 }
125
126The example below is more involved: it takes a function of signature ``int -> int``
127and returns another function of the same kind. The return value is a stateful
128lambda function, which stores the value ``f`` in the capture object and adds 1 to
129its return value upon execution.
130
131.. code-block:: cpp
132
133 std::function<int(int)> func_ret(const std::function<int(int)> &f) {
134 return [f](int i) {
135 return f(i) + 1;
136 };
137 }
138
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200139After including the extra header file :file:`pybind11/functional.h`, it is almost
Wenzel Jakob93296692015-10-13 23:21:54 +0200140trivial to generate binding code for both of these functions.
141
142.. code-block:: cpp
143
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200144 #include <pybind11/functional.h>
Wenzel Jakob93296692015-10-13 23:21:54 +0200145
Wenzel Jakobb1b71402015-10-18 16:48:30 +0200146 PYBIND11_PLUGIN(example) {
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200147 py::module m("example", "pybind11 example plugin");
Wenzel Jakob93296692015-10-13 23:21:54 +0200148
149 m.def("func_arg", &func_arg);
150 m.def("func_ret", &func_ret);
151
152 return m.ptr();
153 }
154
155The following interactive session shows how to call them from Python.
156
157.. code-block:: python
158
159 $ python
160 >>> import example
161 >>> def square(i):
162 ... return i * i
163 ...
164 >>> example.func_arg(square)
165 100L
166 >>> square_plus_1 = example.func_ret(square)
167 >>> square_plus_1(4)
168 17L
169 >>>
170
171.. note::
172
173 This functionality is very useful when generating bindings for callbacks in
174 C++ libraries (e.g. a graphical user interface library).
175
176 The file :file:`example/example5.cpp` contains a complete example that
177 demonstrates how to work with callbacks and anonymous functions in more detail.
178
Wenzel Jakoba4175d62015-11-17 08:30:34 +0100179.. warning::
180
181 Keep in mind that passing a function from C++ to Python (or vice versa)
182 will instantiate a piece of wrapper code that translates function
183 invocations between the two languages. Copying the same function back and
184 forth between Python and C++ many times in a row will cause these wrappers
185 to accumulate, which can decrease performance.
186
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200187Overriding virtual functions in Python
188======================================
189
Wenzel Jakob93296692015-10-13 23:21:54 +0200190Suppose that a C++ class or interface has a virtual function that we'd like to
191to override from within Python (we'll focus on the class ``Animal``; ``Dog`` is
192given as a specific example of how one would do this with traditional C++
193code).
194
195.. code-block:: cpp
196
197 class Animal {
198 public:
199 virtual ~Animal() { }
200 virtual std::string go(int n_times) = 0;
201 };
202
203 class Dog : public Animal {
204 public:
205 std::string go(int n_times) {
206 std::string result;
207 for (int i=0; i<n_times; ++i)
208 result += "woof! ";
209 return result;
210 }
211 };
212
213Let's also suppose that we are given a plain function which calls the
214function ``go()`` on an arbitrary ``Animal`` instance.
215
216.. code-block:: cpp
217
218 std::string call_go(Animal *animal) {
219 return animal->go(3);
220 }
221
222Normally, the binding code for these classes would look as follows:
223
224.. code-block:: cpp
225
Wenzel Jakobb1b71402015-10-18 16:48:30 +0200226 PYBIND11_PLUGIN(example) {
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200227 py::module m("example", "pybind11 example plugin");
Wenzel Jakob93296692015-10-13 23:21:54 +0200228
229 py::class_<Animal> animal(m, "Animal");
230 animal
231 .def("go", &Animal::go);
232
233 py::class_<Dog>(m, "Dog", animal)
234 .def(py::init<>());
235
236 m.def("call_go", &call_go);
237
238 return m.ptr();
239 }
240
241However, these bindings are impossible to extend: ``Animal`` is not
242constructible, and we clearly require some kind of "trampoline" that
243redirects virtual calls back to Python.
244
245Defining a new type of ``Animal`` from within Python is possible but requires a
246helper class that is defined as follows:
247
248.. code-block:: cpp
249
250 class PyAnimal : public Animal {
251 public:
252 /* Inherit the constructors */
253 using Animal::Animal;
254
255 /* Trampoline (need one for each virtual function) */
256 std::string go(int n_times) {
Wenzel Jakobb1b71402015-10-18 16:48:30 +0200257 PYBIND11_OVERLOAD_PURE(
Wenzel Jakob93296692015-10-13 23:21:54 +0200258 std::string, /* Return type */
259 Animal, /* Parent class */
260 go, /* Name of function */
261 n_times /* Argument(s) */
262 );
263 }
264 };
265
Wenzel Jakobb1b71402015-10-18 16:48:30 +0200266The macro :func:`PYBIND11_OVERLOAD_PURE` should be used for pure virtual
267functions, and :func:`PYBIND11_OVERLOAD` should be used for functions which have
Wenzel Jakob93296692015-10-13 23:21:54 +0200268a default implementation. The binding code also needs a few minor adaptations
269(highlighted):
270
271.. code-block:: cpp
272 :emphasize-lines: 4,6,7
273
Wenzel Jakobb1b71402015-10-18 16:48:30 +0200274 PYBIND11_PLUGIN(example) {
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200275 py::module m("example", "pybind11 example plugin");
Wenzel Jakob93296692015-10-13 23:21:54 +0200276
277 py::class_<PyAnimal> animal(m, "Animal");
278 animal
279 .alias<Animal>()
280 .def(py::init<>())
281 .def("go", &Animal::go);
282
283 py::class_<Dog>(m, "Dog", animal)
284 .def(py::init<>());
285
286 m.def("call_go", &call_go);
287
288 return m.ptr();
289 }
290
291Importantly, the trampoline helper class is used as the template argument to
292:class:`class_`, and a call to :func:`class_::alias` informs the binding
293generator that this is merely an alias for the underlying type ``Animal``.
294Following this, we are able to define a constructor as usual.
295
296The Python session below shows how to override ``Animal::go`` and invoke it via
297a virtual method call.
298
Wenzel Jakobde3ad072016-02-02 11:38:21 +0100299.. code-block:: python
Wenzel Jakob93296692015-10-13 23:21:54 +0200300
301 >>> from example import *
302 >>> d = Dog()
303 >>> call_go(d)
304 u'woof! woof! woof! '
305 >>> class Cat(Animal):
306 ... def go(self, n_times):
307 ... return "meow! " * n_times
308 ...
309 >>> c = Cat()
310 >>> call_go(c)
311 u'meow! meow! meow! '
312
313.. seealso::
314
315 The file :file:`example/example12.cpp` contains a complete example that
316 demonstrates how to override virtual functions using pybind11 in more
317 detail.
318
Wenzel Jakobecdd8682015-12-07 18:17:58 +0100319
320Global Interpreter Lock (GIL)
321=============================
322
323The classes :class:`gil_scoped_release` and :class:`gil_scoped_acquire` can be
324used to acquire and release the global interpreter lock in the body of a C++
325function call. In this way, long-running C++ code can be parallelized using
326multiple Python threads. Taking the previous section as an example, this could
327be realized as follows (important changes highlighted):
328
329.. code-block:: cpp
330 :emphasize-lines: 8,9,33,34
331
332 class PyAnimal : public Animal {
333 public:
334 /* Inherit the constructors */
335 using Animal::Animal;
336
337 /* Trampoline (need one for each virtual function) */
338 std::string go(int n_times) {
339 /* Acquire GIL before calling Python code */
Wenzel Jakoba4caa852015-12-14 12:39:02 +0100340 py::gil_scoped_acquire acquire;
Wenzel Jakobecdd8682015-12-07 18:17:58 +0100341
342 PYBIND11_OVERLOAD_PURE(
343 std::string, /* Return type */
344 Animal, /* Parent class */
345 go, /* Name of function */
346 n_times /* Argument(s) */
347 );
348 }
349 };
350
351 PYBIND11_PLUGIN(example) {
352 py::module m("example", "pybind11 example plugin");
353
354 py::class_<PyAnimal> animal(m, "Animal");
355 animal
356 .alias<Animal>()
357 .def(py::init<>())
358 .def("go", &Animal::go);
359
360 py::class_<Dog>(m, "Dog", animal)
361 .def(py::init<>());
362
363 m.def("call_go", [](Animal *animal) -> std::string {
364 /* Release GIL before calling into (potentially long-running) C++ code */
Wenzel Jakoba4caa852015-12-14 12:39:02 +0100365 py::gil_scoped_release release;
Wenzel Jakobecdd8682015-12-07 18:17:58 +0100366 return call_go(animal);
367 });
368
369 return m.ptr();
370 }
371
Wenzel Jakob93296692015-10-13 23:21:54 +0200372Passing STL data structures
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200373===========================
374
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200375When including the additional header file :file:`pybind11/stl.h`, conversions
Wenzel Jakob978e3762016-04-07 18:00:41 +0200376between ``std::vector<>``, ``std::list<>``, ``std::set<>``, and ``std::map<>``
377and the Python ``list``, ``set`` and ``dict`` data structures are automatically
378enabled. The types ``std::pair<>`` and ``std::tuple<>`` are already supported
379out of the box with just the core :file:`pybind11/pybind11.h` header.
Wenzel Jakob93296692015-10-13 23:21:54 +0200380
381.. note::
382
Wenzel Jakob44db04f2015-12-14 12:40:45 +0100383 Arbitrary nesting of any of these types is supported.
Wenzel Jakob93296692015-10-13 23:21:54 +0200384
385.. seealso::
386
387 The file :file:`example/example2.cpp` contains a complete example that
388 demonstrates how to pass STL data types in more detail.
389
390Binding sequence data types, the slicing protocol, etc.
391=======================================================
392
393Please refer to the supplemental example for details.
394
395.. seealso::
396
397 The file :file:`example/example6.cpp` contains a complete example that
398 shows how to bind a sequence data type, including length queries
399 (``__len__``), iterators (``__iter__``), the slicing protocol and other
400 kinds of useful operations.
401
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200402Return value policies
403=====================
404
Wenzel Jakob93296692015-10-13 23:21:54 +0200405Python and C++ use wildly different ways of managing the memory and lifetime of
406objects managed by them. This can lead to issues when creating bindings for
407functions that return a non-trivial type. Just by looking at the type
408information, it is not clear whether Python should take charge of the returned
409value and eventually free its resources, or if this is handled on the C++ side.
410For this reason, pybind11 provides a several `return value policy` annotations
411that can be passed to the :func:`module::def` and :func:`class_::def`
Wenzel Jakob61d67f02015-12-14 12:53:06 +0100412functions. The default policy is :enum:`return_value_policy::automatic`.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200413
Wenzel Jakob93296692015-10-13 23:21:54 +0200414
415+--------------------------------------------------+---------------------------------------------------------------------------+
416| Return value policy | Description |
417+==================================================+===========================================================================+
418| :enum:`return_value_policy::automatic` | Automatic: copy objects returned as values and take ownership of |
419| | objects returned as pointers |
420+--------------------------------------------------+---------------------------------------------------------------------------+
421| :enum:`return_value_policy::copy` | Create a new copy of the returned object, which will be owned by Python |
422+--------------------------------------------------+---------------------------------------------------------------------------+
423| :enum:`return_value_policy::take_ownership` | Reference the existing object and take ownership. Python will call |
424| | the destructor and delete operator when the reference count reaches zero |
425+--------------------------------------------------+---------------------------------------------------------------------------+
426| :enum:`return_value_policy::reference` | Reference the object, but do not take ownership and defer responsibility |
427| | for deleting it to C++ (dangerous when C++ code at some point decides to |
428| | delete it while Python still has a nonzero reference count) |
429+--------------------------------------------------+---------------------------------------------------------------------------+
430| :enum:`return_value_policy::reference_internal` | Reference the object, but do not take ownership. The object is considered |
431| | be owned by the C++ instance whose method or property returned it. The |
432| | Python object will increase the reference count of this 'parent' by 1 |
433| | to ensure that it won't be deallocated while Python is using the 'child' |
434+--------------------------------------------------+---------------------------------------------------------------------------+
435
436.. warning::
437
438 Code with invalid call policies might access unitialized memory and free
439 data structures multiple times, which can lead to hard-to-debug
440 non-determinism and segmentation faults, hence it is worth spending the
441 time to understand all the different options above.
442
443See below for an example that uses the
444:enum:`return_value_policy::reference_internal` policy.
445
446.. code-block:: cpp
447
448 class Example {
449 public:
450 Internal &get_internal() { return internal; }
451 private:
452 Internal internal;
453 };
454
Wenzel Jakobb1b71402015-10-18 16:48:30 +0200455 PYBIND11_PLUGIN(example) {
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200456 py::module m("example", "pybind11 example plugin");
Wenzel Jakob93296692015-10-13 23:21:54 +0200457
458 py::class_<Example>(m, "Example")
459 .def(py::init<>())
Wenzel Jakob978e3762016-04-07 18:00:41 +0200460 .def("get_internal", &Example::get_internal, "Return the internal data", py::return_value_policy::reference_internal);
Wenzel Jakob93296692015-10-13 23:21:54 +0200461
462 return m.ptr();
463 }
464
Wenzel Jakob5f218b32016-01-17 22:36:39 +0100465
466Additional call policies
467========================
468
469In addition to the above return value policies, further `call policies` can be
470specified to indicate dependencies between parameters. There is currently just
471one policy named ``keep_alive<Nurse, Patient>``, which indicates that the
472argument with index ``Patient`` should be kept alive at least until the
473argument with index ``Nurse`` is freed by the garbage collector; argument
474indices start at one, while zero refers to the return value. Arbitrarily many
475call policies can be specified.
476
477For instance, binding code for a a list append operation that ties the lifetime
478of the newly added element to the underlying container might be declared as
479follows:
480
481.. code-block:: cpp
482
483 py::class_<List>(m, "List")
484 .def("append", &List::append, py::keep_alive<1, 2>());
485
486.. note::
487
488 ``keep_alive`` is analogous to the ``with_custodian_and_ward`` (if Nurse,
489 Patient != 0) and ``with_custodian_and_ward_postcall`` (if Nurse/Patient ==
490 0) policies from Boost.Python.
491
Wenzel Jakob61587162016-01-18 22:38:52 +0100492.. seealso::
493
494 The file :file:`example/example13.cpp` contains a complete example that
495 demonstrates using :class:`keep_alive` in more detail.
496
Wenzel Jakob93296692015-10-13 23:21:54 +0200497Implicit type conversions
498=========================
499
500Suppose that instances of two types ``A`` and ``B`` are used in a project, and
501that an ``A`` can easily be converted into a an instance of type ``B`` (examples of this
502could be a fixed and an arbitrary precision number type).
503
504.. code-block:: cpp
505
506 py::class_<A>(m, "A")
507 /// ... members ...
508
509 py::class_<B>(m, "B")
510 .def(py::init<A>())
511 /// ... members ...
512
513 m.def("func",
514 [](const B &) { /* .... */ }
515 );
516
517To invoke the function ``func`` using a variable ``a`` containing an ``A``
518instance, we'd have to write ``func(B(a))`` in Python. On the other hand, C++
519will automatically apply an implicit type conversion, which makes it possible
520to directly write ``func(a)``.
521
522In this situation (i.e. where ``B`` has a constructor that converts from
523``A``), the following statement enables similar implicit conversions on the
524Python side:
525
526.. code-block:: cpp
527
528 py::implicitly_convertible<A, B>();
529
Wenzel Jakob9f0dfce2016-04-06 17:38:18 +0200530Unique pointers
531===============
532
533Given a class ``Example`` with Python bindings, it's possible to return
534instances wrapped in C++11 unique pointers, like so
535
536.. code-block:: cpp
537
538 std::unique_ptr<Example> create_example() { return std::unique_ptr<Example>(new Example()); }
539
540.. code-block:: cpp
541
542 m.def("create_example", &create_example);
543
544In other words, there is nothing special that needs to be done. While returning
545unique pointers in this way is allowed, it is *illegal* to use them as function
546arguments. For instance, the following function signature cannot be processed
547by pybind11.
548
549.. code-block:: cpp
550
551 void do_something_with_example(std::unique_ptr<Example> ex) { ... }
552
553The above signature would imply that Python needs to give up ownership of an
554object that is passed to this function, which is generally not possible (for
555instance, the object might be referenced elsewhere).
556
Wenzel Jakob93296692015-10-13 23:21:54 +0200557Smart pointers
558==============
559
Wenzel Jakob9f0dfce2016-04-06 17:38:18 +0200560This section explains how to pass values that are wrapped in "smart" pointer
561types with internal reference counting. For simpler C++11 unique pointers,
562please refer to the previous section.
563
Wenzel Jakob93296692015-10-13 23:21:54 +0200564The binding generator for classes (:class:`class_`) takes an optional second
565template type, which denotes a special *holder* type that is used to manage
566references to the object. When wrapping a type named ``Type``, the default
567value of this template parameter is ``std::unique_ptr<Type>``, which means that
568the object is deallocated when Python's reference count goes to zero.
569
Wenzel Jakob1853b652015-10-18 15:38:50 +0200570It is possible to switch to other types of reference counting wrappers or smart
571pointers, which is useful in codebases that rely on them. For instance, the
572following snippet causes ``std::shared_ptr`` to be used instead.
Wenzel Jakob93296692015-10-13 23:21:54 +0200573
574.. code-block:: cpp
575
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100576 py::class_<Example, std::shared_ptr<Example> /* <- holder type */> obj(m, "Example");
Wenzel Jakob5ef12192015-12-15 17:07:35 +0100577
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100578Note that any particular class can only be associated with a single holder type.
Wenzel Jakob93296692015-10-13 23:21:54 +0200579
Wenzel Jakob1853b652015-10-18 15:38:50 +0200580To enable transparent conversions for functions that take shared pointers as an
Wenzel Jakob5ef12192015-12-15 17:07:35 +0100581argument or that return them, a macro invocation similar to the following must
Wenzel Jakob1853b652015-10-18 15:38:50 +0200582be declared at the top level before any binding code:
583
584.. code-block:: cpp
585
Wenzel Jakobb1b71402015-10-18 16:48:30 +0200586 PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>);
Wenzel Jakob1853b652015-10-18 15:38:50 +0200587
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100588.. note::
Wenzel Jakob61d67f02015-12-14 12:53:06 +0100589
590 The first argument of :func:`PYBIND11_DECLARE_HOLDER_TYPE` should be a
591 placeholder name that is used as a template parameter of the second
592 argument. Thus, feel free to use any identifier, but use it consistently on
593 both sides; also, don't use the name of a type that already exists in your
594 codebase.
595
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100596One potential stumbling block when using holder types is that they need to be
597applied consistently. Can you guess what's broken about the following binding
598code?
Wenzel Jakob6e213c92015-11-24 23:05:58 +0100599
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100600.. code-block:: cpp
Wenzel Jakob6e213c92015-11-24 23:05:58 +0100601
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100602 class Child { };
Wenzel Jakob5ef12192015-12-15 17:07:35 +0100603
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100604 class Parent {
605 public:
606 Parent() : child(std::make_shared<Child>()) { }
607 Child *get_child() { return child.get(); } /* Hint: ** DON'T DO THIS ** */
608 private:
609 std::shared_ptr<Child> child;
610 };
Wenzel Jakob5ef12192015-12-15 17:07:35 +0100611
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100612 PYBIND11_PLUGIN(example) {
613 py::module m("example");
Wenzel Jakob5ef12192015-12-15 17:07:35 +0100614
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100615 py::class_<Child, std::shared_ptr<Child>>(m, "Child");
616
617 py::class_<Parent, std::shared_ptr<Parent>>(m, "Parent")
618 .def(py::init<>())
619 .def("get_child", &Parent::get_child);
620
621 return m.ptr();
622 }
623
624The following Python code will cause undefined behavior (and likely a
625segmentation fault).
626
627.. code-block:: python
628
629 from example import Parent
630 print(Parent().get_child())
631
632The problem is that ``Parent::get_child()`` returns a pointer to an instance of
633``Child``, but the fact that this instance is already managed by
634``std::shared_ptr<...>`` is lost when passing raw pointers. In this case,
635pybind11 will create a second independent ``std::shared_ptr<...>`` that also
636claims ownership of the pointer. In the end, the object will be freed **twice**
637since these shared pointers have no way of knowing about each other.
638
639There are two ways to resolve this issue:
640
6411. For types that are managed by a smart pointer class, never use raw pointers
642 in function arguments or return values. In other words: always consistently
643 wrap pointers into their designated holder types (such as
644 ``std::shared_ptr<...>``). In this case, the signature of ``get_child()``
645 should be modified as follows:
646
647.. code-block:: cpp
648
649 std::shared_ptr<Child> get_child() { return child; }
650
6512. Adjust the definition of ``Child`` by specifying
652 ``std::enable_shared_from_this<T>`` (see cppreference_ for details) as a
653 base class. This adds a small bit of information to ``Child`` that allows
654 pybind11 to realize that there is already an existing
655 ``std::shared_ptr<...>`` and communicate with it. In this case, the
656 declaration of ``Child`` should look as follows:
Wenzel Jakob5ef12192015-12-15 17:07:35 +0100657
Wenzel Jakob6e213c92015-11-24 23:05:58 +0100658.. _cppreference: http://en.cppreference.com/w/cpp/memory/enable_shared_from_this
659
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100660.. code-block:: cpp
661
662 class Child : public std::enable_shared_from_this<Child> { };
663
Wenzel Jakob5ef12192015-12-15 17:07:35 +0100664.. seealso::
665
666 The file :file:`example/example8.cpp` contains a complete example that
667 demonstrates how to work with custom reference-counting holder types in
668 more detail.
669
Wenzel Jakob93296692015-10-13 23:21:54 +0200670.. _custom_constructors:
671
672Custom constructors
673===================
674
675The syntax for binding constructors was previously introduced, but it only
676works when a constructor with the given parameters actually exists on the C++
677side. To extend this to more general cases, let's take a look at what actually
678happens under the hood: the following statement
679
680.. code-block:: cpp
681
682 py::class_<Example>(m, "Example")
683 .def(py::init<int>());
684
685is short hand notation for
686
687.. code-block:: cpp
688
689 py::class_<Example>(m, "Example")
690 .def("__init__",
691 [](Example &instance, int arg) {
692 new (&instance) Example(arg);
693 }
694 );
695
696In other words, :func:`init` creates an anonymous function that invokes an
697in-place constructor. Memory allocation etc. is already take care of beforehand
698within pybind11.
699
700Catching and throwing exceptions
701================================
702
703When C++ code invoked from Python throws an ``std::exception``, it is
704automatically converted into a Python ``Exception``. pybind11 defines multiple
705special exception classes that will map to different types of Python
706exceptions:
707
Wenzel Jakob978e3762016-04-07 18:00:41 +0200708+--------------------------------------+------------------------------+
709| C++ exception type | Python exception type |
710+======================================+==============================+
711| :class:`std::exception` | ``RuntimeError`` |
712+--------------------------------------+------------------------------+
713| :class:`std::bad_alloc` | ``MemoryError`` |
714+--------------------------------------+------------------------------+
715| :class:`std::domain_error` | ``ValueError`` |
716+--------------------------------------+------------------------------+
717| :class:`std::invalid_argument` | ``ValueError`` |
718+--------------------------------------+------------------------------+
719| :class:`std::length_error` | ``ValueError`` |
720+--------------------------------------+------------------------------+
721| :class:`std::out_of_range` | ``ValueError`` |
722+--------------------------------------+------------------------------+
723| :class:`std::range_error` | ``ValueError`` |
724+--------------------------------------+------------------------------+
725| :class:`pybind11::stop_iteration` | ``StopIteration`` (used to |
726| | implement custom iterators) |
727+--------------------------------------+------------------------------+
728| :class:`pybind11::index_error` | ``IndexError`` (used to |
729| | indicate out of bounds |
730| | accesses in ``__getitem__``, |
731| | ``__setitem__``, etc.) |
732+--------------------------------------+------------------------------+
733| :class:`pybind11::error_already_set` | Indicates that the Python |
734| | exception flag has already |
735| | been initialized |
736+--------------------------------------+------------------------------+
Wenzel Jakob93296692015-10-13 23:21:54 +0200737
738When a Python function invoked from C++ throws an exception, it is converted
739into a C++ exception of type :class:`error_already_set` whose string payload
740contains a textual summary.
741
742There is also a special exception :class:`cast_error` that is thrown by
743:func:`handle::call` when the input arguments cannot be converted to Python
744objects.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200745
746Buffer protocol
747===============
748
749Python supports an extremely general and convenient approach for exchanging
Wenzel Jakob978e3762016-04-07 18:00:41 +0200750data between plugin libraries. Types can expose a buffer view [#f1]_,
751which provides fast direct access to the raw internal representation. Suppose
752we want to bind the following simplistic Matrix class:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200753
754.. code-block:: cpp
755
756 class Matrix {
757 public:
758 Matrix(size_t rows, size_t cols) : m_rows(rows), m_cols(cols) {
759 m_data = new float[rows*cols];
760 }
761 float *data() { return m_data; }
762 size_t rows() const { return m_rows; }
763 size_t cols() const { return m_cols; }
764 private:
765 size_t m_rows, m_cols;
766 float *m_data;
767 };
768
769The following binding code exposes the ``Matrix`` contents as a buffer object,
770making it possible to cast Matrixes into NumPy arrays. It is even possible to
771completely avoid copy operations with Python expressions like
772``np.array(matrix_instance, copy = False)``.
773
774.. code-block:: cpp
775
776 py::class_<Matrix>(m, "Matrix")
777 .def_buffer([](Matrix &m) -> py::buffer_info {
778 return py::buffer_info(
779 m.data(), /* Pointer to buffer */
780 sizeof(float), /* Size of one scalar */
781 py::format_descriptor<float>::value(), /* Python struct-style format descriptor */
782 2, /* Number of dimensions */
783 { m.rows(), m.cols() }, /* Buffer dimensions */
784 { sizeof(float) * m.rows(), /* Strides (in bytes) for each index */
785 sizeof(float) }
786 );
787 });
788
789The snippet above binds a lambda function, which can create ``py::buffer_info``
790description records on demand describing a given matrix. The contents of
791``py::buffer_info`` mirror the Python buffer protocol specification.
792
793.. code-block:: cpp
794
795 struct buffer_info {
796 void *ptr;
797 size_t itemsize;
798 std::string format;
799 int ndim;
800 std::vector<size_t> shape;
801 std::vector<size_t> strides;
802 };
803
804To create a C++ function that can take a Python buffer object as an argument,
805simply use the type ``py::buffer`` as one of its arguments. Buffers can exist
806in a great variety of configurations, hence some safety checks are usually
807necessary in the function body. Below, you can see an basic example on how to
808define a custom constructor for the Eigen double precision matrix
809(``Eigen::MatrixXd``) type, which supports initialization from compatible
810buffer
811objects (e.g. a NumPy matrix).
812
813.. code-block:: cpp
814
815 py::class_<Eigen::MatrixXd>(m, "MatrixXd")
816 .def("__init__", [](Eigen::MatrixXd &m, py::buffer b) {
817 /* Request a buffer descriptor from Python */
818 py::buffer_info info = b.request();
819
820 /* Some sanity checks ... */
821 if (info.format != py::format_descriptor<double>::value())
822 throw std::runtime_error("Incompatible format: expected a double array!");
823
824 if (info.ndim != 2)
825 throw std::runtime_error("Incompatible buffer dimension!");
826
827 if (info.strides[0] == sizeof(double)) {
828 /* Buffer has the right layout -- directly copy. */
829 new (&m) Eigen::MatrixXd(info.shape[0], info.shape[1]);
830 memcpy(m.data(), info.ptr, sizeof(double) * m.size());
831 } else {
832 /* Oops -- the buffer is transposed */
833 new (&m) Eigen::MatrixXd(info.shape[1], info.shape[0]);
834 memcpy(m.data(), info.ptr, sizeof(double) * m.size());
835 m.transposeInPlace();
836 }
837 });
838
Wenzel Jakob93296692015-10-13 23:21:54 +0200839.. seealso::
840
841 The file :file:`example/example7.cpp` contains a complete example that
842 demonstrates using the buffer protocol with pybind11 in more detail.
843
Wenzel Jakob978e3762016-04-07 18:00:41 +0200844.. [#f1] https://docs.python.org/3/c-api/buffer.html
845
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200846NumPy support
847=============
848
849By exchanging ``py::buffer`` with ``py::array`` in the above snippet, we can
850restrict the function so that it only accepts NumPy arrays (rather than any
Wenzel Jakob978e3762016-04-07 18:00:41 +0200851type of Python object satisfying the buffer protocol).
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200852
853In many situations, we want to define a function which only accepts a NumPy
Wenzel Jakob93296692015-10-13 23:21:54 +0200854array of a certain data type. This is possible via the ``py::array_t<T>``
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200855template. For instance, the following function requires the argument to be a
856dense array of doubles in C-style ordering.
857
858.. code-block:: cpp
859
Wenzel Jakob93296692015-10-13 23:21:54 +0200860 void f(py::array_t<double> array);
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200861
862When it is invoked with a different type (e.g. an integer), the binding code
Wenzel Jakob978e3762016-04-07 18:00:41 +0200863will attempt to cast the input into a NumPy array of the requested type. Note
864that this feature requires the :file:``pybind11/numpy.h`` header to be
865included.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200866
867Vectorizing functions
868=====================
869
870Suppose we want to bind a function with the following signature to Python so
871that it can process arbitrary NumPy array arguments (vectors, matrices, general
872N-D arrays) in addition to its normal arguments:
873
874.. code-block:: cpp
875
876 double my_func(int x, float y, double z);
877
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200878After including the ``pybind11/numpy.h`` header, this is extremely simple:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200879
880.. code-block:: cpp
881
882 m.def("vectorized_func", py::vectorize(my_func));
883
884Invoking the function like below causes 4 calls to be made to ``my_func`` with
Wenzel Jakob978e3762016-04-07 18:00:41 +0200885each of the the array elements. The significant advantage of this compared to
886solutions like ``numpy.vectorize()`` is that the loop over the elements runs
887entirely on the C++ side and can be crunched down into a tight, optimized loop
888by the compiler. The result is returned as a NumPy array of type
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200889``numpy.dtype.float64``.
890
891.. code-block:: python
892
893 >>> x = np.array([[1, 3],[5, 7]])
894 >>> y = np.array([[2, 4],[6, 8]])
895 >>> z = 3
896 >>> result = vectorized_func(x, y, z)
897
898The scalar argument ``z`` is transparently replicated 4 times. The input
899arrays ``x`` and ``y`` are automatically converted into the right types (they
900are of type ``numpy.dtype.int64`` but need to be ``numpy.dtype.int32`` and
901``numpy.dtype.float32``, respectively)
902
903Sometimes we might want to explitly exclude an argument from the vectorization
904because it makes little sense to wrap it in a NumPy array. For instance,
905suppose the function signature was
906
907.. code-block:: cpp
908
909 double my_func(int x, float y, my_custom_type *z);
910
911This can be done with a stateful Lambda closure:
912
913.. code-block:: cpp
914
915 // Vectorize a lambda function with a capture object (e.g. to exclude some arguments from the vectorization)
916 m.def("vectorized_func",
Wenzel Jakob93296692015-10-13 23:21:54 +0200917 [](py::array_t<int> x, py::array_t<float> y, my_custom_type *z) {
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200918 auto stateful_closure = [z](int x, float y) { return my_func(x, y, z); };
919 return py::vectorize(stateful_closure)(x, y);
920 }
921 );
922
Wenzel Jakob61587162016-01-18 22:38:52 +0100923In cases where the computation is too complicated to be reduced to
924``vectorize``, it will be necessary to create and access the buffer contents
925manually. The following snippet contains a complete example that shows how this
926works (the code is somewhat contrived, since it could have been done more
927simply using ``vectorize``).
928
929.. code-block:: cpp
930
931 #include <pybind11/pybind11.h>
932 #include <pybind11/numpy.h>
933
934 namespace py = pybind11;
935
936 py::array_t<double> add_arrays(py::array_t<double> input1, py::array_t<double> input2) {
937 auto buf1 = input1.request(), buf2 = input2.request();
938
939 if (buf1.ndim != 1 || buf2.ndim != 1)
940 throw std::runtime_error("Number of dimensions must be one");
941
942 if (buf1.shape[0] != buf2.shape[0])
943 throw std::runtime_error("Input shapes must match");
944
945 auto result = py::array(py::buffer_info(
946 nullptr, /* Pointer to data (nullptr -> ask NumPy to allocate!) */
947 sizeof(double), /* Size of one item */
948 py::format_descriptor<double>::value(), /* Buffer format */
949 buf1.ndim, /* How many dimensions? */
950 { buf1.shape[0] }, /* Number of elements for each dimension */
951 { sizeof(double) } /* Strides for each dimension */
952 ));
953
954 auto buf3 = result.request();
955
956 double *ptr1 = (double *) buf1.ptr,
957 *ptr2 = (double *) buf2.ptr,
958 *ptr3 = (double *) buf3.ptr;
959
960 for (size_t idx = 0; idx < buf1.shape[0]; idx++)
961 ptr3[idx] = ptr1[idx] + ptr2[idx];
962
963 return result;
964 }
965
966 PYBIND11_PLUGIN(test) {
967 py::module m("test");
968 m.def("add_arrays", &add_arrays, "Add two NumPy arrays");
969 return m.ptr();
970 }
971
Wenzel Jakob93296692015-10-13 23:21:54 +0200972.. seealso::
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200973
Wenzel Jakob93296692015-10-13 23:21:54 +0200974 The file :file:`example/example10.cpp` contains a complete example that
975 demonstrates using :func:`vectorize` in more detail.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200976
Wenzel Jakob93296692015-10-13 23:21:54 +0200977Functions taking Python objects as arguments
978============================================
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200979
Wenzel Jakob93296692015-10-13 23:21:54 +0200980pybind11 exposes all major Python types using thin C++ wrapper classes. These
981wrapper classes can also be used as parameters of functions in bindings, which
982makes it possible to directly work with native Python types on the C++ side.
983For instance, the following statement iterates over a Python ``dict``:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200984
Wenzel Jakob93296692015-10-13 23:21:54 +0200985.. code-block:: cpp
986
987 void print_dict(py::dict dict) {
988 /* Easily interact with Python types */
989 for (auto item : dict)
990 std::cout << "key=" << item.first << ", "
991 << "value=" << item.second << std::endl;
992 }
993
994Available types include :class:`handle`, :class:`object`, :class:`bool_`,
Wenzel Jakob27e8e102016-01-17 22:36:37 +0100995:class:`int_`, :class:`float_`, :class:`str`, :class:`bytes`, :class:`tuple`,
996:class:`list`, :class:`dict`, :class:`slice`, :class:`capsule`,
997:class:`function`, :class:`buffer`, :class:`array`, and :class:`array_t`.
Wenzel Jakob93296692015-10-13 23:21:54 +0200998
Wenzel Jakob436b7312015-10-20 01:04:30 +0200999In this kind of mixed code, it is often necessary to convert arbitrary C++
1000types to Python, which can be done using :func:`cast`:
1001
1002.. code-block:: cpp
1003
1004 MyClass *cls = ..;
1005 py::object obj = py::cast(cls);
1006
1007The reverse direction uses the following syntax:
1008
1009.. code-block:: cpp
1010
1011 py::object obj = ...;
1012 MyClass *cls = obj.cast<MyClass *>();
1013
1014When conversion fails, both directions throw the exception :class:`cast_error`.
1015
Wenzel Jakob93296692015-10-13 23:21:54 +02001016.. seealso::
1017
1018 The file :file:`example/example2.cpp` contains a complete example that
1019 demonstrates passing native Python types in more detail.
Wenzel Jakob2ac50442016-01-17 22:36:35 +01001020
1021Default arguments revisited
1022===========================
1023
1024The section on :ref:`default_args` previously discussed basic usage of default
1025arguments using pybind11. One noteworthy aspect of their implementation is that
1026default arguments are converted to Python objects right at declaration time.
1027Consider the following example:
1028
1029.. code-block:: cpp
1030
1031 py::class_<MyClass>("MyClass")
1032 .def("myFunction", py::arg("arg") = SomeType(123));
1033
1034In this case, pybind11 must already be set up to deal with values of the type
1035``SomeType`` (via a prior instantiation of ``py::class_<SomeType>``), or an
1036exception will be thrown.
1037
1038Another aspect worth highlighting is that the "preview" of the default argument
1039in the function signature is generated using the object's ``__repr__`` method.
1040If not available, the signature may not be very helpful, e.g.:
1041
1042.. code-block:: python
1043
1044 FUNCTIONS
1045 ...
1046 | myFunction(...)
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001047 | Signature : (MyClass, arg : SomeType = <SomeType object at 0x101b7b080>) -> NoneType
Wenzel Jakob2ac50442016-01-17 22:36:35 +01001048 ...
1049
1050The first way of addressing this is by defining ``SomeType.__repr__``.
1051Alternatively, it is possible to specify the human-readable preview of the
1052default argument manually using the ``arg_t`` notation:
1053
1054.. code-block:: cpp
1055
1056 py::class_<MyClass>("MyClass")
1057 .def("myFunction", py::arg_t<SomeType>("arg", SomeType(123), "SomeType(123)"));
1058
Wenzel Jakobc769fce2016-03-03 12:03:30 +01001059Sometimes it may be necessary to pass a null pointer value as a default
1060argument. In this case, remember to cast it to the underlying type in question,
1061like so:
1062
1063.. code-block:: cpp
1064
1065 py::class_<MyClass>("MyClass")
1066 .def("myFunction", py::arg("arg") = (SomeType *) nullptr);
1067
Wenzel Jakob2dfbade2016-01-17 22:36:37 +01001068Partitioning code over multiple extension modules
1069=================================================
1070
Wenzel Jakob8d862b32016-03-06 13:37:22 +01001071It's straightforward to split binding code over multiple extension modules, while
1072referencing types that are declared elsewhere. Everything "just" works without any special
Wenzel Jakobeda978e2016-03-15 15:05:40 +01001073precautions. One exception to this rule occurs when extending a type declared
Wenzel Jakob2dfbade2016-01-17 22:36:37 +01001074in another extension module. Recall the basic example from Section
1075:ref:`inheritance`.
1076
1077.. code-block:: cpp
1078
1079 py::class_<Pet> pet(m, "Pet");
1080 pet.def(py::init<const std::string &>())
1081 .def_readwrite("name", &Pet::name);
1082
1083 py::class_<Dog>(m, "Dog", pet /* <- specify parent */)
1084 .def(py::init<const std::string &>())
1085 .def("bark", &Dog::bark);
1086
1087Suppose now that ``Pet`` bindings are defined in a module named ``basic``,
1088whereas the ``Dog`` bindings are defined somewhere else. The challenge is of
1089course that the variable ``pet`` is not available anymore though it is needed
1090to indicate the inheritance relationship to the constructor of ``class_<Dog>``.
1091However, it can be acquired as follows:
1092
1093.. code-block:: cpp
1094
1095 py::object pet = (py::object) py::module::import("basic").attr("Pet");
1096
1097 py::class_<Dog>(m, "Dog", pet)
1098 .def(py::init<const std::string &>())
1099 .def("bark", &Dog::bark);
1100
Wenzel Jakob8d862b32016-03-06 13:37:22 +01001101Alternatively, we can rely on the ``base`` tag, which performs an automated
1102lookup of the corresponding Python type. However, this also requires invoking
1103the ``import`` function once to ensure that the pybind11 binding code of the
1104module ``basic`` has been executed.
1105
Wenzel Jakob8d862b32016-03-06 13:37:22 +01001106.. code-block:: cpp
1107
1108 py::module::import("basic");
1109
1110 py::class_<Dog>(m, "Dog", py::base<Pet>())
1111 .def(py::init<const std::string &>())
1112 .def("bark", &Dog::bark);
Wenzel Jakobeda978e2016-03-15 15:05:40 +01001113
Wenzel Jakob978e3762016-04-07 18:00:41 +02001114Naturally, both methods will fail when there are cyclic dependencies.
1115
Wenzel Jakobeda978e2016-03-15 15:05:40 +01001116Treating STL data structures as opaque objects
1117==============================================
1118
1119pybind11 heavily relies on a template matching mechanism to convert parameters
1120and return values that are constructed from STL data types such as vectors,
1121linked lists, hash tables, etc. This even works in a recursive manner, for
1122instance to deal with lists of hash maps of pairs of elementary and custom
1123types, etc.
1124
Wenzel Jakob978e3762016-04-07 18:00:41 +02001125A fundamental limitation of this approach is that the internal conversion
1126between Python and C++ types involves a copy operation that prevents
1127pass-by-reference semantics. What does this mean?
Wenzel Jakobeda978e2016-03-15 15:05:40 +01001128
1129Suppose we bind the following function
1130
1131.. code-block:: cpp
1132
1133 void append_1(std::vector<int> &v) {
1134 v.push_back(1);
1135 }
1136
1137and call it as follows from Python:
1138
1139.. code-block:: python
1140
1141 >>> v = [5, 6]
1142 >>> append_1(v)
1143 >>> print(v)
1144 [5, 6]
1145
1146As you can see, when passing STL data structures by reference, modifications
1147are not propagated back the Python side. To deal with situations where this
1148desirable, pybind11 contains a simple template wrapper class named ``opaque<T>``.
1149
1150``opaque<T>`` disables the underlying template machinery for
1151``T`` and can be used to treat STL types as opaque objects, whose contents are
1152never inspected or extracted (thus, they can be passed by reference).
1153The downside of this approach is that it the binding code becomes a bit more
1154wordy. The above function can be bound using the following wrapper code:
1155
1156.. code-block:: cpp
1157
1158 m.def("append_1", [](py::opaque<std::vector<int>> &v) { append_1(v); });
1159
1160Opaque types must also have a dedicated ``class_`` declaration to define a
1161set of admissible operations.
1162
1163.. seealso::
1164
1165 The file :file:`example/example14.cpp` contains a complete example that
1166 demonstrates how to create opaque types using pybind11 in more detail.