You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

113 lines
3.9 KiB

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