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.

81 lines
2.7 KiB

8 years ago
  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. NAMESPACE_BEGIN(pybind11)
  11. 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) {
  19. if (src_.is_none())
  20. return true;
  21. src_ = detail::get_function(src_);
  22. if (!src_ || !PyCallable_Check(src_.ptr()))
  23. return false;
  24. /*
  25. When passing a C++ function as an argument to another C++
  26. function via Python, every function call would normally involve
  27. a full C++ -> Python -> C++ roundtrip, which can be prohibitive.
  28. Here, we try to at least detect the case where the function is
  29. stateless (i.e. function pointer or lambda function without
  30. captured variables), in which case the roundtrip can be avoided.
  31. */
  32. if (PyCFunction_Check(src_.ptr())) {
  33. auto c = reinterpret_borrow<capsule>(PyCFunction_GET_SELF(src_.ptr()));
  34. auto rec = (function_record *) c;
  35. if (rec && rec->is_stateless && rec->data[1] == &typeid(function_type)) {
  36. struct capture { function_type f; };
  37. value = ((capture *) &rec->data)->f;
  38. return true;
  39. }
  40. }
  41. auto src = reinterpret_borrow<object>(src_);
  42. value = [src](Args... args) -> Return {
  43. gil_scoped_acquire acq;
  44. object retval(src(std::forward<Args>(args)...));
  45. /* Visual studio 2015 parser issue: need parentheses around this expression */
  46. return (retval.template cast<Return>());
  47. };
  48. return true;
  49. }
  50. template <typename Func>
  51. static handle cast(Func &&f_, return_value_policy policy, handle /* parent */) {
  52. if (!f_)
  53. return none().inc_ref();
  54. auto result = f_.template target<function_type>();
  55. if (result)
  56. return cpp_function(*result, policy).release();
  57. else
  58. return cpp_function(std::forward<Func>(f_), policy).release();
  59. }
  60. PYBIND11_TYPE_CASTER(type, _("Callable[[") +
  61. argument_loader<Args...>::arg_names() + _("], ") +
  62. make_caster<retval_type>::name() +
  63. _("]"));
  64. };
  65. NAMESPACE_END(detail)
  66. NAMESPACE_END(pybind11)