blob: 5d0a01d13eab6946d5b3679e3caa9b0cfa4db713 [file] [log] [blame]
Dean Moldovan67b52d82016-10-16 19:12:43 +02001Functional
2##########
3
4The following features must be enabled by including :file:`pybind11/functional.h`.
5
6
7Callbacks and passing anonymous functions
8=========================================
9
10The C++11 standard brought lambda functions and the generic polymorphic
11function wrapper ``std::function<>`` to the C++ programming language, which
12enable powerful new ways of working with functions. Lambda functions come in
13two flavors: stateless lambda function resemble classic function pointers that
14link to an anonymous piece of code, while stateful lambda functions
15additionally depend on captured variables that are stored in an anonymous
16*lambda closure object*.
17
18Here is a simple example of a C++ function that takes an arbitrary function
19(stateful or stateless) with signature ``int -> int`` as an argument and runs
20it with the value 10.
21
22.. code-block:: cpp
23
24 int func_arg(const std::function<int(int)> &f) {
25 return f(10);
26 }
27
28The example below is more involved: it takes a function of signature ``int -> int``
29and returns another function of the same kind. The return value is a stateful
30lambda function, which stores the value ``f`` in the capture object and adds 1 to
31its return value upon execution.
32
33.. code-block:: cpp
34
35 std::function<int(int)> func_ret(const std::function<int(int)> &f) {
36 return [f](int i) {
37 return f(i) + 1;
38 };
39 }
40
41This example demonstrates using python named parameters in C++ callbacks which
42requires using ``py::cpp_function`` as a wrapper. Usage is similar to defining
43methods of classes:
44
45.. code-block:: cpp
46
47 py::cpp_function func_cpp() {
48 return py::cpp_function([](int i) { return i+1; },
49 py::arg("number"));
50 }
51
52After including the extra header file :file:`pybind11/functional.h`, it is almost
53trivial to generate binding code for all of these functions.
54
55.. code-block:: cpp
56
57 #include <pybind11/functional.h>
58
59 PYBIND11_PLUGIN(example) {
60 py::module m("example", "pybind11 example plugin");
61
62 m.def("func_arg", &func_arg);
63 m.def("func_ret", &func_ret);
64 m.def("func_cpp", &func_cpp);
65
66 return m.ptr();
67 }
68
69The following interactive session shows how to call them from Python.
70
71.. code-block:: pycon
72
73 $ python
74 >>> import example
75 >>> def square(i):
76 ... return i * i
77 ...
78 >>> example.func_arg(square)
79 100L
80 >>> square_plus_1 = example.func_ret(square)
81 >>> square_plus_1(4)
82 17L
83 >>> plus_1 = func_cpp()
84 >>> plus_1(number=43)
85 44L
86
87.. warning::
88
89 Keep in mind that passing a function from C++ to Python (or vice versa)
90 will instantiate a piece of wrapper code that translates function
91 invocations between the two languages. Naturally, this translation
92 increases the computational cost of each function call somewhat. A
93 problematic situation can arise when a function is copied back and forth
94 between Python and C++ many times in a row, in which case the underlying
95 wrappers will accumulate correspondingly. The resulting long sequence of
96 C++ -> Python -> C++ -> ... roundtrips can significantly decrease
97 performance.
98
99 There is one exception: pybind11 detects case where a stateless function
100 (i.e. a function pointer or a lambda function without captured variables)
101 is passed as an argument to another C++ function exposed in Python. In this
102 case, there is no overhead. Pybind11 will extract the underlying C++
103 function pointer from the wrapped function to sidestep a potential C++ ->
104 Python -> C++ roundtrip. This is demonstrated in :file:`tests/test_callbacks.cpp`.
105
106.. note::
107
108 This functionality is very useful when generating bindings for callbacks in
109 C++ libraries (e.g. GUI libraries, asynchronous networking libraries, etc.).
110
111 The file :file:`tests/test_callbacks.cpp` contains a complete example
112 that demonstrates how to work with callbacks and anonymous functions in
113 more detail.