blob: 4caacf9c06981754428410099c0aa9e14a4b32e2 [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 Jakob28f98aa2015-10-13 02:57:16 +020015Operator overloading
16====================
17
Wenzel Jakob93296692015-10-13 23:21:54 +020018Suppose that we're given the following ``Vector2`` class with a vector addition
19and scalar multiplication operation, all implemented using overloaded operators
20in 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
41The following snippet shows how the above operators can be conveniently exposed
42to Python.
43
44.. code-block:: cpp
45
Wenzel Jakob8f4eb002015-10-15 18:13:33 +020046 #include <pybind11/operators.h>
Wenzel Jakob93296692015-10-13 23:21:54 +020047
Wenzel Jakobb1b71402015-10-18 16:48:30 +020048 PYBIND11_PLUGIN(example) {
Wenzel Jakob8f4eb002015-10-15 18:13:33 +020049 py::module m("example", "pybind11 example plugin");
Wenzel Jakob93296692015-10-13 23:21:54 +020050
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
62Note that a line like
63
64.. code-block:: cpp
65
66 .def(py::self * float())
67
68is 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
76This can be useful for exposing additional operators that don't exist on the
77C++ side, or to perform other types of customization.
78
79.. note::
80
81 To use the more convenient ``py::self`` notation, the additional
Wenzel Jakob8f4eb002015-10-15 18:13:33 +020082 header file :file:`pybind11/operators.h` must be included.
Wenzel Jakob93296692015-10-13 23:21:54 +020083
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
89Callbacks and passing anonymous functions
90=========================================
91
92The C++11 standard brought lambda functions and the generic polymorphic
93function wrapper ``std::function<>`` to the C++ programming language, which
94enable powerful new ways of working with functions. Lambda functions come in
95two flavors: stateless lambda function resemble classic function pointers that
96link to an anonymous piece of code, while stateful lambda functions
97additionally depend on captured variables that are stored in an anonymous
98*lambda closure object*.
99
100Here 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
102it 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
110The example below is more involved: it takes a function of signature ``int -> int``
111and returns another function of the same kind. The return value is a stateful
112lambda function, which stores the value ``f`` in the capture object and adds 1 to
113its 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 Jakob8f4eb002015-10-15 18:13:33 +0200123After including the extra header file :file:`pybind11/functional.h`, it is almost
Wenzel Jakob93296692015-10-13 23:21:54 +0200124trivial to generate binding code for both of these functions.
125
126.. code-block:: cpp
127
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200128 #include <pybind11/functional.h>
Wenzel Jakob93296692015-10-13 23:21:54 +0200129
Wenzel Jakobb1b71402015-10-18 16:48:30 +0200130 PYBIND11_PLUGIN(example) {
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200131 py::module m("example", "pybind11 example plugin");
Wenzel Jakob93296692015-10-13 23:21:54 +0200132
133 m.def("func_arg", &func_arg);
134 m.def("func_ret", &func_ret);
135
136 return m.ptr();
137 }
138
139The 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 Jakob28f98aa2015-10-13 02:57:16 +0200163Overriding virtual functions in Python
164======================================
165
Wenzel Jakob93296692015-10-13 23:21:54 +0200166Suppose that a C++ class or interface has a virtual function that we'd like to
167to override from within Python (we'll focus on the class ``Animal``; ``Dog`` is
168given as a specific example of how one would do this with traditional C++
169code).
170
171.. code-block:: cpp
172
173 class Animal {
174 public:
175 virtual ~Animal() { }
176 virtual std::string go(int n_times) = 0;
177 };
178
179 class Dog : public Animal {
180 public:
181 std::string go(int n_times) {
182 std::string result;
183 for (int i=0; i<n_times; ++i)
184 result += "woof! ";
185 return result;
186 }
187 };
188
189Let's also suppose that we are given a plain function which calls the
190function ``go()`` on an arbitrary ``Animal`` instance.
191
192.. code-block:: cpp
193
194 std::string call_go(Animal *animal) {
195 return animal->go(3);
196 }
197
198Normally, the binding code for these classes would look as follows:
199
200.. code-block:: cpp
201
Wenzel Jakobb1b71402015-10-18 16:48:30 +0200202 PYBIND11_PLUGIN(example) {
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200203 py::module m("example", "pybind11 example plugin");
Wenzel Jakob93296692015-10-13 23:21:54 +0200204
205 py::class_<Animal> animal(m, "Animal");
206 animal
207 .def("go", &Animal::go);
208
209 py::class_<Dog>(m, "Dog", animal)
210 .def(py::init<>());
211
212 m.def("call_go", &call_go);
213
214 return m.ptr();
215 }
216
217However, these bindings are impossible to extend: ``Animal`` is not
218constructible, and we clearly require some kind of "trampoline" that
219redirects virtual calls back to Python.
220
221Defining a new type of ``Animal`` from within Python is possible but requires a
222helper class that is defined as follows:
223
224.. code-block:: cpp
225
226 class PyAnimal : public Animal {
227 public:
228 /* Inherit the constructors */
229 using Animal::Animal;
230
231 /* Trampoline (need one for each virtual function) */
232 std::string go(int n_times) {
Wenzel Jakobb1b71402015-10-18 16:48:30 +0200233 PYBIND11_OVERLOAD_PURE(
Wenzel Jakob93296692015-10-13 23:21:54 +0200234 std::string, /* Return type */
235 Animal, /* Parent class */
236 go, /* Name of function */
237 n_times /* Argument(s) */
238 );
239 }
240 };
241
Wenzel Jakobb1b71402015-10-18 16:48:30 +0200242The macro :func:`PYBIND11_OVERLOAD_PURE` should be used for pure virtual
243functions, and :func:`PYBIND11_OVERLOAD` should be used for functions which have
Wenzel Jakob93296692015-10-13 23:21:54 +0200244a default implementation. The binding code also needs a few minor adaptations
245(highlighted):
246
247.. code-block:: cpp
248 :emphasize-lines: 4,6,7
249
Wenzel Jakobb1b71402015-10-18 16:48:30 +0200250 PYBIND11_PLUGIN(example) {
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200251 py::module m("example", "pybind11 example plugin");
Wenzel Jakob93296692015-10-13 23:21:54 +0200252
253 py::class_<PyAnimal> animal(m, "Animal");
254 animal
255 .alias<Animal>()
256 .def(py::init<>())
257 .def("go", &Animal::go);
258
259 py::class_<Dog>(m, "Dog", animal)
260 .def(py::init<>());
261
262 m.def("call_go", &call_go);
263
264 return m.ptr();
265 }
266
267Importantly, the trampoline helper class is used as the template argument to
268:class:`class_`, and a call to :func:`class_::alias` informs the binding
269generator that this is merely an alias for the underlying type ``Animal``.
270Following this, we are able to define a constructor as usual.
271
272The Python session below shows how to override ``Animal::go`` and invoke it via
273a virtual method call.
274
275.. code-block:: cpp
276
277 >>> from example import *
278 >>> d = Dog()
279 >>> call_go(d)
280 u'woof! woof! woof! '
281 >>> class Cat(Animal):
282 ... def go(self, n_times):
283 ... return "meow! " * n_times
284 ...
285 >>> c = Cat()
286 >>> call_go(c)
287 u'meow! meow! meow! '
288
289.. seealso::
290
291 The file :file:`example/example12.cpp` contains a complete example that
292 demonstrates how to override virtual functions using pybind11 in more
293 detail.
294
295Passing STL data structures
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200296===========================
297
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200298When including the additional header file :file:`pybind11/stl.h`, conversions
Wenzel Jakob93296692015-10-13 23:21:54 +0200299between ``std::vector<>`` and ``std::map<>`` and the Python ``list`` and
300``dict`` data structures are automatically enabled. The types ``std::pair<>``
301and ``std::tuple<>`` are already supported out of the box with just the core
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200302:file:`pybind11/pybind11.h` header.
Wenzel Jakob93296692015-10-13 23:21:54 +0200303
304.. note::
305
306 Arbitrary nesting of any of these types is explicitly permitted.
307
308.. seealso::
309
310 The file :file:`example/example2.cpp` contains a complete example that
311 demonstrates how to pass STL data types in more detail.
312
313Binding sequence data types, the slicing protocol, etc.
314=======================================================
315
316Please refer to the supplemental example for details.
317
318.. seealso::
319
320 The file :file:`example/example6.cpp` contains a complete example that
321 shows how to bind a sequence data type, including length queries
322 (``__len__``), iterators (``__iter__``), the slicing protocol and other
323 kinds of useful operations.
324
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200325Return value policies
326=====================
327
Wenzel Jakob93296692015-10-13 23:21:54 +0200328Python and C++ use wildly different ways of managing the memory and lifetime of
329objects managed by them. This can lead to issues when creating bindings for
330functions that return a non-trivial type. Just by looking at the type
331information, it is not clear whether Python should take charge of the returned
332value and eventually free its resources, or if this is handled on the C++ side.
333For this reason, pybind11 provides a several `return value policy` annotations
334that can be passed to the :func:`module::def` and :func:`class_::def`
335functions. The default policy is :enum:`return_value_policy::automatic``.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200336
Wenzel Jakob93296692015-10-13 23:21:54 +0200337
338+--------------------------------------------------+---------------------------------------------------------------------------+
339| Return value policy | Description |
340+==================================================+===========================================================================+
341| :enum:`return_value_policy::automatic` | Automatic: copy objects returned as values and take ownership of |
342| | objects returned as pointers |
343+--------------------------------------------------+---------------------------------------------------------------------------+
344| :enum:`return_value_policy::copy` | Create a new copy of the returned object, which will be owned by Python |
345+--------------------------------------------------+---------------------------------------------------------------------------+
346| :enum:`return_value_policy::take_ownership` | Reference the existing object and take ownership. Python will call |
347| | the destructor and delete operator when the reference count reaches zero |
348+--------------------------------------------------+---------------------------------------------------------------------------+
349| :enum:`return_value_policy::reference` | Reference the object, but do not take ownership and defer responsibility |
350| | for deleting it to C++ (dangerous when C++ code at some point decides to |
351| | delete it while Python still has a nonzero reference count) |
352+--------------------------------------------------+---------------------------------------------------------------------------+
353| :enum:`return_value_policy::reference_internal` | Reference the object, but do not take ownership. The object is considered |
354| | be owned by the C++ instance whose method or property returned it. The |
355| | Python object will increase the reference count of this 'parent' by 1 |
356| | to ensure that it won't be deallocated while Python is using the 'child' |
357+--------------------------------------------------+---------------------------------------------------------------------------+
358
359.. warning::
360
361 Code with invalid call policies might access unitialized memory and free
362 data structures multiple times, which can lead to hard-to-debug
363 non-determinism and segmentation faults, hence it is worth spending the
364 time to understand all the different options above.
365
366See below for an example that uses the
367:enum:`return_value_policy::reference_internal` policy.
368
369.. code-block:: cpp
370
371 class Example {
372 public:
373 Internal &get_internal() { return internal; }
374 private:
375 Internal internal;
376 };
377
Wenzel Jakobb1b71402015-10-18 16:48:30 +0200378 PYBIND11_PLUGIN(example) {
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200379 py::module m("example", "pybind11 example plugin");
Wenzel Jakob93296692015-10-13 23:21:54 +0200380
381 py::class_<Example>(m, "Example")
382 .def(py::init<>())
383 .def("get_internal", &Example::get_internal, "Return the internal data", py::return_value_policy::reference_internal)
384
385 return m.ptr();
386 }
387
388Implicit type conversions
389=========================
390
391Suppose that instances of two types ``A`` and ``B`` are used in a project, and
392that an ``A`` can easily be converted into a an instance of type ``B`` (examples of this
393could be a fixed and an arbitrary precision number type).
394
395.. code-block:: cpp
396
397 py::class_<A>(m, "A")
398 /// ... members ...
399
400 py::class_<B>(m, "B")
401 .def(py::init<A>())
402 /// ... members ...
403
404 m.def("func",
405 [](const B &) { /* .... */ }
406 );
407
408To invoke the function ``func`` using a variable ``a`` containing an ``A``
409instance, we'd have to write ``func(B(a))`` in Python. On the other hand, C++
410will automatically apply an implicit type conversion, which makes it possible
411to directly write ``func(a)``.
412
413In this situation (i.e. where ``B`` has a constructor that converts from
414``A``), the following statement enables similar implicit conversions on the
415Python side:
416
417.. code-block:: cpp
418
419 py::implicitly_convertible<A, B>();
420
421Smart pointers
422==============
423
424The binding generator for classes (:class:`class_`) takes an optional second
425template type, which denotes a special *holder* type that is used to manage
426references to the object. When wrapping a type named ``Type``, the default
427value of this template parameter is ``std::unique_ptr<Type>``, which means that
428the object is deallocated when Python's reference count goes to zero.
429
Wenzel Jakob1853b652015-10-18 15:38:50 +0200430It is possible to switch to other types of reference counting wrappers or smart
431pointers, which is useful in codebases that rely on them. For instance, the
432following snippet causes ``std::shared_ptr`` to be used instead.
Wenzel Jakob93296692015-10-13 23:21:54 +0200433
434.. code-block:: cpp
435
436 py::class_<Example, std::shared_ptr<Example>> obj(m, "Example");
437
Wenzel Jakob1853b652015-10-18 15:38:50 +0200438To enable transparent conversions for functions that take shared pointers as an
439argument or that return them, a macro invocation similar to the following must
440be declared at the top level before any binding code:
441
442.. code-block:: cpp
443
Wenzel Jakobb1b71402015-10-18 16:48:30 +0200444 PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>);
Wenzel Jakob1853b652015-10-18 15:38:50 +0200445
Wenzel Jakob93296692015-10-13 23:21:54 +0200446.. seealso::
447
448 The file :file:`example/example8.cpp` contains a complete example that
Wenzel Jakob1853b652015-10-18 15:38:50 +0200449 demonstrates how to work with custom reference-counting holder types in
450 more detail.
Wenzel Jakob93296692015-10-13 23:21:54 +0200451
452.. _custom_constructors:
453
454Custom constructors
455===================
456
457The syntax for binding constructors was previously introduced, but it only
458works when a constructor with the given parameters actually exists on the C++
459side. To extend this to more general cases, let's take a look at what actually
460happens under the hood: the following statement
461
462.. code-block:: cpp
463
464 py::class_<Example>(m, "Example")
465 .def(py::init<int>());
466
467is short hand notation for
468
469.. code-block:: cpp
470
471 py::class_<Example>(m, "Example")
472 .def("__init__",
473 [](Example &instance, int arg) {
474 new (&instance) Example(arg);
475 }
476 );
477
478In other words, :func:`init` creates an anonymous function that invokes an
479in-place constructor. Memory allocation etc. is already take care of beforehand
480within pybind11.
481
482Catching and throwing exceptions
483================================
484
485When C++ code invoked from Python throws an ``std::exception``, it is
486automatically converted into a Python ``Exception``. pybind11 defines multiple
487special exception classes that will map to different types of Python
488exceptions:
489
490+----------------------------+------------------------------+
491| C++ exception type | Python exception type |
492+============================+==============================+
493| :class:`std::exception` | ``Exception`` |
494+----------------------------+------------------------------+
495| :class:`stop_iteration` | ``StopIteration`` (used to |
496| | implement custom iterators) |
497+----------------------------+------------------------------+
498| :class:`index_error` | ``IndexError`` (used to |
499| | indicate out of bounds |
500| | accesses in ``__getitem__``, |
501| | ``__setitem__``, etc.) |
502+----------------------------+------------------------------+
503| :class:`error_already_set` | Indicates that the Python |
504| | exception flag has already |
505| | been initialized. |
506+----------------------------+------------------------------+
507
508When a Python function invoked from C++ throws an exception, it is converted
509into a C++ exception of type :class:`error_already_set` whose string payload
510contains a textual summary.
511
512There is also a special exception :class:`cast_error` that is thrown by
513:func:`handle::call` when the input arguments cannot be converted to Python
514objects.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200515
516Buffer protocol
517===============
518
519Python supports an extremely general and convenient approach for exchanging
520data between plugin libraries. Types can expose a buffer view which provides
521fast direct access to the raw internal representation. Suppose we want to bind
522the following simplistic Matrix class:
523
524.. code-block:: cpp
525
526 class Matrix {
527 public:
528 Matrix(size_t rows, size_t cols) : m_rows(rows), m_cols(cols) {
529 m_data = new float[rows*cols];
530 }
531 float *data() { return m_data; }
532 size_t rows() const { return m_rows; }
533 size_t cols() const { return m_cols; }
534 private:
535 size_t m_rows, m_cols;
536 float *m_data;
537 };
538
539The following binding code exposes the ``Matrix`` contents as a buffer object,
540making it possible to cast Matrixes into NumPy arrays. It is even possible to
541completely avoid copy operations with Python expressions like
542``np.array(matrix_instance, copy = False)``.
543
544.. code-block:: cpp
545
546 py::class_<Matrix>(m, "Matrix")
547 .def_buffer([](Matrix &m) -> py::buffer_info {
548 return py::buffer_info(
549 m.data(), /* Pointer to buffer */
550 sizeof(float), /* Size of one scalar */
551 py::format_descriptor<float>::value(), /* Python struct-style format descriptor */
552 2, /* Number of dimensions */
553 { m.rows(), m.cols() }, /* Buffer dimensions */
554 { sizeof(float) * m.rows(), /* Strides (in bytes) for each index */
555 sizeof(float) }
556 );
557 });
558
559The snippet above binds a lambda function, which can create ``py::buffer_info``
560description records on demand describing a given matrix. The contents of
561``py::buffer_info`` mirror the Python buffer protocol specification.
562
563.. code-block:: cpp
564
565 struct buffer_info {
566 void *ptr;
567 size_t itemsize;
568 std::string format;
569 int ndim;
570 std::vector<size_t> shape;
571 std::vector<size_t> strides;
572 };
573
574To create a C++ function that can take a Python buffer object as an argument,
575simply use the type ``py::buffer`` as one of its arguments. Buffers can exist
576in a great variety of configurations, hence some safety checks are usually
577necessary in the function body. Below, you can see an basic example on how to
578define a custom constructor for the Eigen double precision matrix
579(``Eigen::MatrixXd``) type, which supports initialization from compatible
580buffer
581objects (e.g. a NumPy matrix).
582
583.. code-block:: cpp
584
585 py::class_<Eigen::MatrixXd>(m, "MatrixXd")
586 .def("__init__", [](Eigen::MatrixXd &m, py::buffer b) {
587 /* Request a buffer descriptor from Python */
588 py::buffer_info info = b.request();
589
590 /* Some sanity checks ... */
591 if (info.format != py::format_descriptor<double>::value())
592 throw std::runtime_error("Incompatible format: expected a double array!");
593
594 if (info.ndim != 2)
595 throw std::runtime_error("Incompatible buffer dimension!");
596
597 if (info.strides[0] == sizeof(double)) {
598 /* Buffer has the right layout -- directly copy. */
599 new (&m) Eigen::MatrixXd(info.shape[0], info.shape[1]);
600 memcpy(m.data(), info.ptr, sizeof(double) * m.size());
601 } else {
602 /* Oops -- the buffer is transposed */
603 new (&m) Eigen::MatrixXd(info.shape[1], info.shape[0]);
604 memcpy(m.data(), info.ptr, sizeof(double) * m.size());
605 m.transposeInPlace();
606 }
607 });
608
Wenzel Jakob93296692015-10-13 23:21:54 +0200609.. seealso::
610
611 The file :file:`example/example7.cpp` contains a complete example that
612 demonstrates using the buffer protocol with pybind11 in more detail.
613
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200614NumPy support
615=============
616
617By exchanging ``py::buffer`` with ``py::array`` in the above snippet, we can
618restrict the function so that it only accepts NumPy arrays (rather than any
619type of Python object satisfying the buffer object protocol).
620
621In many situations, we want to define a function which only accepts a NumPy
Wenzel Jakob93296692015-10-13 23:21:54 +0200622array of a certain data type. This is possible via the ``py::array_t<T>``
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200623template. For instance, the following function requires the argument to be a
624dense array of doubles in C-style ordering.
625
626.. code-block:: cpp
627
Wenzel Jakob93296692015-10-13 23:21:54 +0200628 void f(py::array_t<double> array);
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200629
630When it is invoked with a different type (e.g. an integer), the binding code
631will attempt to cast the input into a NumPy array of the requested type.
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200632Note that this feature requires the ``pybind11/numpy.h`` header to be included.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200633
634Vectorizing functions
635=====================
636
637Suppose we want to bind a function with the following signature to Python so
638that it can process arbitrary NumPy array arguments (vectors, matrices, general
639N-D arrays) in addition to its normal arguments:
640
641.. code-block:: cpp
642
643 double my_func(int x, float y, double z);
644
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200645After including the ``pybind11/numpy.h`` header, this is extremely simple:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200646
647.. code-block:: cpp
648
649 m.def("vectorized_func", py::vectorize(my_func));
650
651Invoking the function like below causes 4 calls to be made to ``my_func`` with
652each of the the array elements. The result is returned as a NumPy array of type
653``numpy.dtype.float64``.
654
655.. code-block:: python
656
657 >>> x = np.array([[1, 3],[5, 7]])
658 >>> y = np.array([[2, 4],[6, 8]])
659 >>> z = 3
660 >>> result = vectorized_func(x, y, z)
661
662The scalar argument ``z`` is transparently replicated 4 times. The input
663arrays ``x`` and ``y`` are automatically converted into the right types (they
664are of type ``numpy.dtype.int64`` but need to be ``numpy.dtype.int32`` and
665``numpy.dtype.float32``, respectively)
666
667Sometimes we might want to explitly exclude an argument from the vectorization
668because it makes little sense to wrap it in a NumPy array. For instance,
669suppose the function signature was
670
671.. code-block:: cpp
672
673 double my_func(int x, float y, my_custom_type *z);
674
675This can be done with a stateful Lambda closure:
676
677.. code-block:: cpp
678
679 // Vectorize a lambda function with a capture object (e.g. to exclude some arguments from the vectorization)
680 m.def("vectorized_func",
Wenzel Jakob93296692015-10-13 23:21:54 +0200681 [](py::array_t<int> x, py::array_t<float> y, my_custom_type *z) {
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200682 auto stateful_closure = [z](int x, float y) { return my_func(x, y, z); };
683 return py::vectorize(stateful_closure)(x, y);
684 }
685 );
686
Wenzel Jakob93296692015-10-13 23:21:54 +0200687.. seealso::
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200688
Wenzel Jakob93296692015-10-13 23:21:54 +0200689 The file :file:`example/example10.cpp` contains a complete example that
690 demonstrates using :func:`vectorize` in more detail.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200691
Wenzel Jakob93296692015-10-13 23:21:54 +0200692Functions taking Python objects as arguments
693============================================
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200694
Wenzel Jakob93296692015-10-13 23:21:54 +0200695pybind11 exposes all major Python types using thin C++ wrapper classes. These
696wrapper classes can also be used as parameters of functions in bindings, which
697makes it possible to directly work with native Python types on the C++ side.
698For instance, the following statement iterates over a Python ``dict``:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200699
Wenzel Jakob93296692015-10-13 23:21:54 +0200700.. code-block:: cpp
701
702 void print_dict(py::dict dict) {
703 /* Easily interact with Python types */
704 for (auto item : dict)
705 std::cout << "key=" << item.first << ", "
706 << "value=" << item.second << std::endl;
707 }
708
709Available types include :class:`handle`, :class:`object`, :class:`bool_`,
710:class:`int_`, :class:`float_`, :class:`str`, :class:`tuple`, :class:`list`,
711:class:`dict`, :class:`slice`, :class:`capsule`, :class:`function`,
712:class:`buffer`, :class:`array`, and :class:`array_t`.
713
714.. seealso::
715
716 The file :file:`example/example2.cpp` contains a complete example that
717 demonstrates passing native Python types in more detail.
718