functional.rst revision 11986
12SN/AFunctional
21762SN/A##########
32SN/A
42SN/AThe following features must be enabled by including :file:`pybind11/functional.h`.
52SN/A
62SN/A
72SN/ACallbacks and passing anonymous functions
82SN/A=========================================
92SN/A
102SN/AThe C++11 standard brought lambda functions and the generic polymorphic
112SN/Afunction wrapper ``std::function<>`` to the C++ programming language, which
122SN/Aenable powerful new ways of working with functions. Lambda functions come in
132SN/Atwo flavors: stateless lambda function resemble classic function pointers that
142SN/Alink to an anonymous piece of code, while stateful lambda functions
152SN/Aadditionally depend on captured variables that are stored in an anonymous
162SN/A*lambda closure object*.
172SN/A
182SN/AHere is a simple example of a C++ function that takes an arbitrary function
192SN/A(stateful or stateless) with signature ``int -> int`` as an argument and runs
202SN/Ait with the value 10.
212SN/A
222SN/A.. code-block:: cpp
232SN/A
242SN/A    int func_arg(const std::function<int(int)> &f) {
252SN/A        return f(10);
262SN/A    }
272665Ssaidi@eecs.umich.edu
282665Ssaidi@eecs.umich.eduThe example below is more involved: it takes a function of signature ``int -> int``
292665Ssaidi@eecs.umich.eduand returns another function of the same kind. The return value is a stateful
302SN/Alambda function, which stores the value ``f`` in the capture object and adds 1 to
312SN/Aits return value upon execution.
322SN/A
332SN/A.. code-block:: cpp
34330SN/A
3556SN/A    std::function<int(int)> func_ret(const std::function<int(int)> &f) {
361031SN/A        return [f](int i) {
37330SN/A            return f(i) + 1;
38330SN/A        };
39938SN/A    }
4056SN/A
41330SN/AThis example demonstrates using python named parameters in C++ callbacks which
42695SN/Arequires using ``py::cpp_function`` as a wrapper. Usage is similar to defining
432SN/Amethods of classes:
442SN/A
452SN/A.. code-block:: cpp
462SN/A
472SN/A    py::cpp_function func_cpp() {
482SN/A        return py::cpp_function([](int i) { return i+1; },
492SN/A           py::arg("number"));
502SN/A    }
512SN/A
522SN/AAfter including the extra header file :file:`pybind11/functional.h`, it is almost
532SN/Atrivial to generate binding code for all of these functions.
542SN/A
552SN/A.. code-block:: cpp
562SN/A
572SN/A    #include <pybind11/functional.h>
582SN/A
592SN/A    PYBIND11_PLUGIN(example) {
602SN/A        py::module m("example", "pybind11 example plugin");
614762Snate@binkert.org
621553SN/A        m.def("func_arg", &func_arg);
632SN/A        m.def("func_ret", &func_ret);
641031SN/A        m.def("func_cpp", &func_cpp);
651031SN/A
661031SN/A        return m.ptr();
671031SN/A    }
681553SN/A
692901Ssaidi@eecs.umich.eduThe following interactive session shows how to call them from Python.
701553SN/A
711553SN/A.. code-block:: pycon
724762Snate@binkert.org
735034Smilesck@eecs.umich.edu    $ python
744762Snate@binkert.org    >>> import example
754762Snate@binkert.org    >>> def square(i):
764762Snate@binkert.org    ...     return i * i
774762Snate@binkert.org    ...
784762Snate@binkert.org    >>> example.func_arg(square)
794762Snate@binkert.org    100L
80465SN/A    >>> square_plus_1 = example.func_ret(square)
81465SN/A    >>> square_plus_1(4)
82465SN/A    17L
83465SN/A    >>> plus_1 = func_cpp()
84465SN/A    >>> plus_1(number=43)
852SN/A    44L
862SN/A
872SN/A.. warning::
882SN/A
892SN/A    Keep in mind that passing a function from C++ to Python (or vice versa)
902SN/A    will instantiate a piece of wrapper code that translates function
912SN/A    invocations between the two languages. Naturally, this translation
922SN/A    increases the computational cost of each function call somewhat. A
932SN/A    problematic situation can arise when a function is copied back and forth
942SN/A    between Python and C++ many times in a row, in which case the underlying
952SN/A    wrappers will accumulate correspondingly. The resulting long sequence of
962SN/A    C++ -> Python -> C++ -> ... roundtrips can significantly decrease
972SN/A    performance.
98330SN/A
99330SN/A    There is one exception: pybind11 detects case where a stateless function
100330SN/A    (i.e. a function pointer or a lambda function without captured variables)
101330SN/A    is passed as an argument to another C++ function exposed in Python. In this
102330SN/A    case, there is no overhead. Pybind11 will extract the underlying C++
1032SN/A    function pointer from the wrapped function to sidestep a potential C++ ->
10453SN/A    Python -> C++ roundtrip. This is demonstrated in :file:`tests/test_callbacks.cpp`.
10553SN/A
10653SN/A.. note::
1072SN/A
108334SN/A    This functionality is very useful when generating bindings for callbacks in
109334SN/A    C++ libraries (e.g. GUI libraries, asynchronous networking libraries, etc.).
110334SN/A
111334SN/A    The file :file:`tests/test_callbacks.cpp` contains a complete example
112334SN/A    that demonstrates how to work with callbacks and anonymous functions in
113334SN/A    more detail.
114334SN/A