functional.h 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. /*
  2. pybind11/functional.h: std::function<> support
  3. Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
  4. All rights reserved. Use of this source code is governed by a
  5. BSD-style license that can be found in the LICENSE file.
  6. */
  7. #pragma once
  8. #include "pybind11.h"
  9. #include <functional>
  10. PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
  11. PYBIND11_NAMESPACE_BEGIN(detail)
  12. template <typename Return, typename... Args>
  13. struct type_caster<std::function<Return(Args...)>> {
  14. using type = std::function<Return(Args...)>;
  15. using retval_type = conditional_t<std::is_same<Return, void>::value, void_type, Return>;
  16. using function_type = Return (*)(Args...);
  17. public:
  18. bool load(handle src, bool convert) {
  19. if (src.is_none()) {
  20. // Defer accepting None to other overloads (if we aren't in convert mode):
  21. if (!convert) {
  22. return false;
  23. }
  24. return true;
  25. }
  26. if (!isinstance<function>(src)) {
  27. return false;
  28. }
  29. auto func = reinterpret_borrow<function>(src);
  30. /*
  31. When passing a C++ function as an argument to another C++
  32. function via Python, every function call would normally involve
  33. a full C++ -> Python -> C++ roundtrip, which can be prohibitive.
  34. Here, we try to at least detect the case where the function is
  35. stateless (i.e. function pointer or lambda function without
  36. captured variables), in which case the roundtrip can be avoided.
  37. */
  38. if (auto cfunc = func.cpp_function()) {
  39. auto *cfunc_self = PyCFunction_GET_SELF(cfunc.ptr());
  40. if (isinstance<capsule>(cfunc_self)) {
  41. auto c = reinterpret_borrow<capsule>(cfunc_self);
  42. auto *rec = (function_record *) c;
  43. while (rec != nullptr) {
  44. if (rec->is_stateless
  45. && same_type(typeid(function_type),
  46. *reinterpret_cast<const std::type_info *>(rec->data[1]))) {
  47. struct capture {
  48. function_type f;
  49. };
  50. value = ((capture *) &rec->data)->f;
  51. return true;
  52. }
  53. rec = rec->next;
  54. }
  55. }
  56. // PYPY segfaults here when passing builtin function like sum.
  57. // Raising an fail exception here works to prevent the segfault, but only on gcc.
  58. // See PR #1413 for full details
  59. }
  60. // ensure GIL is held during functor destruction
  61. struct func_handle {
  62. function f;
  63. #if !(defined(_MSC_VER) && _MSC_VER == 1916 && defined(PYBIND11_CPP17))
  64. // This triggers a syntax error under very special conditions (very weird indeed).
  65. explicit
  66. #endif
  67. func_handle(function &&f_) noexcept
  68. : f(std::move(f_)) {
  69. }
  70. func_handle(const func_handle &f_) { operator=(f_); }
  71. func_handle &operator=(const func_handle &f_) {
  72. gil_scoped_acquire acq;
  73. f = f_.f;
  74. return *this;
  75. }
  76. ~func_handle() {
  77. gil_scoped_acquire acq;
  78. function kill_f(std::move(f));
  79. }
  80. };
  81. // to emulate 'move initialization capture' in C++11
  82. struct func_wrapper {
  83. func_handle hfunc;
  84. explicit func_wrapper(func_handle &&hf) noexcept : hfunc(std::move(hf)) {}
  85. Return operator()(Args... args) const {
  86. gil_scoped_acquire acq;
  87. // casts the returned object as a rvalue to the return type
  88. return hfunc.f(std::forward<Args>(args)...).template cast<Return>();
  89. }
  90. };
  91. value = func_wrapper(func_handle(std::move(func)));
  92. return true;
  93. }
  94. template <typename Func>
  95. static handle cast(Func &&f_, return_value_policy policy, handle /* parent */) {
  96. if (!f_) {
  97. return none().release();
  98. }
  99. auto result = f_.template target<function_type>();
  100. if (result) {
  101. return cpp_function(*result, policy).release();
  102. }
  103. return cpp_function(std::forward<Func>(f_), policy).release();
  104. }
  105. PYBIND11_TYPE_CASTER(type,
  106. const_name("Callable[[") + concat(make_caster<Args>::name...)
  107. + const_name("], ") + make_caster<retval_type>::name
  108. + const_name("]"));
  109. };
  110. PYBIND11_NAMESPACE_END(detail)
  111. PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)