blob: 9c07e4f040a5611ca8a5cca44f0cb4afe23765ba [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
48 PYBIND_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
130 PYBIND_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
202 PYBIND_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) {
233 PYBIND_OVERLOAD_PURE(
234 std::string, /* Return type */
235 Animal, /* Parent class */
236 go, /* Name of function */
237 n_times /* Argument(s) */
238 );
239 }
240 };
241
242The macro :func:`PYBIND_OVERLOAD_PURE` should be used for pure virtual
243functions, and :func:`PYBIND_OVERLOAD` should be used for functions which have
244a 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
250 PYBIND_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
378 PYBIND_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
430It is possible to switch to other types of smart pointers, which is useful in
431codebases that rely on them. For instance, the following snippet causes
432``std::shared_ptr`` to be used instead.
433
434.. code-block:: cpp
435
436 py::class_<Example, std::shared_ptr<Example>> obj(m, "Example");
437
438.. seealso::
439
440 The file :file:`example/example8.cpp` contains a complete example that
441 demonstrates how to work with custom smart pointer types in more detail.
442
443.. _custom_constructors:
444
445Custom constructors
446===================
447
448The syntax for binding constructors was previously introduced, but it only
449works when a constructor with the given parameters actually exists on the C++
450side. To extend this to more general cases, let's take a look at what actually
451happens under the hood: the following statement
452
453.. code-block:: cpp
454
455 py::class_<Example>(m, "Example")
456 .def(py::init<int>());
457
458is short hand notation for
459
460.. code-block:: cpp
461
462 py::class_<Example>(m, "Example")
463 .def("__init__",
464 [](Example &instance, int arg) {
465 new (&instance) Example(arg);
466 }
467 );
468
469In other words, :func:`init` creates an anonymous function that invokes an
470in-place constructor. Memory allocation etc. is already take care of beforehand
471within pybind11.
472
473Catching and throwing exceptions
474================================
475
476When C++ code invoked from Python throws an ``std::exception``, it is
477automatically converted into a Python ``Exception``. pybind11 defines multiple
478special exception classes that will map to different types of Python
479exceptions:
480
481+----------------------------+------------------------------+
482| C++ exception type | Python exception type |
483+============================+==============================+
484| :class:`std::exception` | ``Exception`` |
485+----------------------------+------------------------------+
486| :class:`stop_iteration` | ``StopIteration`` (used to |
487| | implement custom iterators) |
488+----------------------------+------------------------------+
489| :class:`index_error` | ``IndexError`` (used to |
490| | indicate out of bounds |
491| | accesses in ``__getitem__``, |
492| | ``__setitem__``, etc.) |
493+----------------------------+------------------------------+
494| :class:`error_already_set` | Indicates that the Python |
495| | exception flag has already |
496| | been initialized. |
497+----------------------------+------------------------------+
498
499When a Python function invoked from C++ throws an exception, it is converted
500into a C++ exception of type :class:`error_already_set` whose string payload
501contains a textual summary.
502
503There is also a special exception :class:`cast_error` that is thrown by
504:func:`handle::call` when the input arguments cannot be converted to Python
505objects.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200506
507Buffer protocol
508===============
509
510Python supports an extremely general and convenient approach for exchanging
511data between plugin libraries. Types can expose a buffer view which provides
512fast direct access to the raw internal representation. Suppose we want to bind
513the following simplistic Matrix class:
514
515.. code-block:: cpp
516
517 class Matrix {
518 public:
519 Matrix(size_t rows, size_t cols) : m_rows(rows), m_cols(cols) {
520 m_data = new float[rows*cols];
521 }
522 float *data() { return m_data; }
523 size_t rows() const { return m_rows; }
524 size_t cols() const { return m_cols; }
525 private:
526 size_t m_rows, m_cols;
527 float *m_data;
528 };
529
530The following binding code exposes the ``Matrix`` contents as a buffer object,
531making it possible to cast Matrixes into NumPy arrays. It is even possible to
532completely avoid copy operations with Python expressions like
533``np.array(matrix_instance, copy = False)``.
534
535.. code-block:: cpp
536
537 py::class_<Matrix>(m, "Matrix")
538 .def_buffer([](Matrix &m) -> py::buffer_info {
539 return py::buffer_info(
540 m.data(), /* Pointer to buffer */
541 sizeof(float), /* Size of one scalar */
542 py::format_descriptor<float>::value(), /* Python struct-style format descriptor */
543 2, /* Number of dimensions */
544 { m.rows(), m.cols() }, /* Buffer dimensions */
545 { sizeof(float) * m.rows(), /* Strides (in bytes) for each index */
546 sizeof(float) }
547 );
548 });
549
550The snippet above binds a lambda function, which can create ``py::buffer_info``
551description records on demand describing a given matrix. The contents of
552``py::buffer_info`` mirror the Python buffer protocol specification.
553
554.. code-block:: cpp
555
556 struct buffer_info {
557 void *ptr;
558 size_t itemsize;
559 std::string format;
560 int ndim;
561 std::vector<size_t> shape;
562 std::vector<size_t> strides;
563 };
564
565To create a C++ function that can take a Python buffer object as an argument,
566simply use the type ``py::buffer`` as one of its arguments. Buffers can exist
567in a great variety of configurations, hence some safety checks are usually
568necessary in the function body. Below, you can see an basic example on how to
569define a custom constructor for the Eigen double precision matrix
570(``Eigen::MatrixXd``) type, which supports initialization from compatible
571buffer
572objects (e.g. a NumPy matrix).
573
574.. code-block:: cpp
575
576 py::class_<Eigen::MatrixXd>(m, "MatrixXd")
577 .def("__init__", [](Eigen::MatrixXd &m, py::buffer b) {
578 /* Request a buffer descriptor from Python */
579 py::buffer_info info = b.request();
580
581 /* Some sanity checks ... */
582 if (info.format != py::format_descriptor<double>::value())
583 throw std::runtime_error("Incompatible format: expected a double array!");
584
585 if (info.ndim != 2)
586 throw std::runtime_error("Incompatible buffer dimension!");
587
588 if (info.strides[0] == sizeof(double)) {
589 /* Buffer has the right layout -- directly copy. */
590 new (&m) Eigen::MatrixXd(info.shape[0], info.shape[1]);
591 memcpy(m.data(), info.ptr, sizeof(double) * m.size());
592 } else {
593 /* Oops -- the buffer is transposed */
594 new (&m) Eigen::MatrixXd(info.shape[1], info.shape[0]);
595 memcpy(m.data(), info.ptr, sizeof(double) * m.size());
596 m.transposeInPlace();
597 }
598 });
599
Wenzel Jakob93296692015-10-13 23:21:54 +0200600.. seealso::
601
602 The file :file:`example/example7.cpp` contains a complete example that
603 demonstrates using the buffer protocol with pybind11 in more detail.
604
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200605NumPy support
606=============
607
608By exchanging ``py::buffer`` with ``py::array`` in the above snippet, we can
609restrict the function so that it only accepts NumPy arrays (rather than any
610type of Python object satisfying the buffer object protocol).
611
612In many situations, we want to define a function which only accepts a NumPy
Wenzel Jakob93296692015-10-13 23:21:54 +0200613array of a certain data type. This is possible via the ``py::array_t<T>``
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200614template. For instance, the following function requires the argument to be a
615dense array of doubles in C-style ordering.
616
617.. code-block:: cpp
618
Wenzel Jakob93296692015-10-13 23:21:54 +0200619 void f(py::array_t<double> array);
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200620
621When it is invoked with a different type (e.g. an integer), the binding code
622will attempt to cast the input into a NumPy array of the requested type.
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200623Note that this feature requires the ``pybind11/numpy.h`` header to be included.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200624
625Vectorizing functions
626=====================
627
628Suppose we want to bind a function with the following signature to Python so
629that it can process arbitrary NumPy array arguments (vectors, matrices, general
630N-D arrays) in addition to its normal arguments:
631
632.. code-block:: cpp
633
634 double my_func(int x, float y, double z);
635
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200636After including the ``pybind11/numpy.h`` header, this is extremely simple:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200637
638.. code-block:: cpp
639
640 m.def("vectorized_func", py::vectorize(my_func));
641
642Invoking the function like below causes 4 calls to be made to ``my_func`` with
643each of the the array elements. The result is returned as a NumPy array of type
644``numpy.dtype.float64``.
645
646.. code-block:: python
647
648 >>> x = np.array([[1, 3],[5, 7]])
649 >>> y = np.array([[2, 4],[6, 8]])
650 >>> z = 3
651 >>> result = vectorized_func(x, y, z)
652
653The scalar argument ``z`` is transparently replicated 4 times. The input
654arrays ``x`` and ``y`` are automatically converted into the right types (they
655are of type ``numpy.dtype.int64`` but need to be ``numpy.dtype.int32`` and
656``numpy.dtype.float32``, respectively)
657
658Sometimes we might want to explitly exclude an argument from the vectorization
659because it makes little sense to wrap it in a NumPy array. For instance,
660suppose the function signature was
661
662.. code-block:: cpp
663
664 double my_func(int x, float y, my_custom_type *z);
665
666This can be done with a stateful Lambda closure:
667
668.. code-block:: cpp
669
670 // Vectorize a lambda function with a capture object (e.g. to exclude some arguments from the vectorization)
671 m.def("vectorized_func",
Wenzel Jakob93296692015-10-13 23:21:54 +0200672 [](py::array_t<int> x, py::array_t<float> y, my_custom_type *z) {
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200673 auto stateful_closure = [z](int x, float y) { return my_func(x, y, z); };
674 return py::vectorize(stateful_closure)(x, y);
675 }
676 );
677
Wenzel Jakob93296692015-10-13 23:21:54 +0200678.. seealso::
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200679
Wenzel Jakob93296692015-10-13 23:21:54 +0200680 The file :file:`example/example10.cpp` contains a complete example that
681 demonstrates using :func:`vectorize` in more detail.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200682
Wenzel Jakob93296692015-10-13 23:21:54 +0200683Functions taking Python objects as arguments
684============================================
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200685
Wenzel Jakob93296692015-10-13 23:21:54 +0200686pybind11 exposes all major Python types using thin C++ wrapper classes. These
687wrapper classes can also be used as parameters of functions in bindings, which
688makes it possible to directly work with native Python types on the C++ side.
689For instance, the following statement iterates over a Python ``dict``:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200690
Wenzel Jakob93296692015-10-13 23:21:54 +0200691.. code-block:: cpp
692
693 void print_dict(py::dict dict) {
694 /* Easily interact with Python types */
695 for (auto item : dict)
696 std::cout << "key=" << item.first << ", "
697 << "value=" << item.second << std::endl;
698 }
699
700Available types include :class:`handle`, :class:`object`, :class:`bool_`,
701:class:`int_`, :class:`float_`, :class:`str`, :class:`tuple`, :class:`list`,
702:class:`dict`, :class:`slice`, :class:`capsule`, :class:`function`,
703:class:`buffer`, :class:`array`, and :class:`array_t`.
704
705.. seealso::
706
707 The file :file:`example/example2.cpp` contains a complete example that
708 demonstrates passing native Python types in more detail.
709