Scarab  v2.11.1
Project 8 C++ Utility Library
functional.h
Go to the documentation of this file.
1 /*
2  pybind11/functional.h: std::function<> support
3 
4  Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
5 
6  All rights reserved. Use of this source code is governed by a
7  BSD-style license that can be found in the LICENSE file.
8 */
9 
10 #pragma once
11 
12 #include "pybind11.h"
13 #include <functional>
14 
16 NAMESPACE_BEGIN(detail)
17 
18 template <typename Return, typename... Args>
19 struct type_caster<std::function<Return(Args...)>> {
20  using type = std::function<Return(Args...)>;
22  using function_type = Return (*) (Args...);
23 
24 public:
25  bool load(handle src, bool convert) {
26  if (src.is_none()) {
27  // Defer accepting None to other overloads (if we aren't in convert mode):
28  if (!convert) return false;
29  return true;
30  }
31 
32  if (!isinstance<function>(src))
33  return false;
34 
35  auto func = reinterpret_borrow<function>(src);
36 
37  /*
38  When passing a C++ function as an argument to another C++
39  function via Python, every function call would normally involve
40  a full C++ -> Python -> C++ roundtrip, which can be prohibitive.
41  Here, we try to at least detect the case where the function is
42  stateless (i.e. function pointer or lambda function without
43  captured variables), in which case the roundtrip can be avoided.
44  */
45  if (auto cfunc = func.cpp_function()) {
46  auto c = reinterpret_borrow<capsule>(PyCFunction_GET_SELF(cfunc.ptr()));
47  auto rec = (function_record *) c;
48 
49  if (rec && rec->is_stateless &&
50  same_type(typeid(function_type), *reinterpret_cast<const std::type_info *>(rec->data[1]))) {
51  struct capture { function_type f; };
52  value = ((capture *) &rec->data)->f;
53  return true;
54  }
55  }
56 
57  // ensure GIL is held during functor destruction
58  struct func_handle {
59  function f;
60  func_handle(function&& f_) : f(std::move(f_)) {}
61  func_handle(const func_handle&) = default;
62  ~func_handle() {
64  function kill_f(std::move(f));
65  }
66  };
67 
68  // to emulate 'move initialization capture' in C++11
69  struct func_wrapper {
70  func_handle hfunc;
71  func_wrapper(func_handle&& hf): hfunc(std::move(hf)) {}
72  Return operator()(Args... args) const {
74  object retval(hfunc.f(std::forward<Args>(args)...));
75  /* Visual studio 2015 parser issue: need parentheses around this expression */
76  return (retval.template cast<Return>());
77  }
78  };
79 
80  value = func_wrapper(func_handle(std::move(func)));
81  return true;
82  }
83 
84  template <typename Func>
85  static handle cast(Func &&f_, return_value_policy policy, handle /* parent */) {
86  if (!f_)
87  return none().inc_ref();
88 
89  auto result = f_.template target<function_type>();
90  if (result)
91  return cpp_function(*result, policy).release();
92  else
93  return cpp_function(std::forward<Func>(f_), policy).release();
94  }
95 
96  PYBIND11_TYPE_CASTER(type, _("Callable[[") + concat(make_caster<Args>::name...) + _("], ")
98 };
99 
100 NAMESPACE_END(detail)
Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object.
Definition: pybind11.h:56
#define PYBIND11_NAMESPACE
Definition: detail/common.h:26
STL namespace.
Internal data structure which holds metadata about a bound function (signature, overloads, etc.)
Definition: attr.h:134
constexpr descr< N - 1 > _(char const(&text)[N])
Definition: descr.h:54
conditional_t< std::is_same< Return, void >::value, void_type, Return > retval_type
Definition: functional.h:21
bool same_type(const std::type_info &lhs, const std::type_info &rhs)
Definition: internals.h:59
bool is_none() const
Equivalent to obj is None in Python.
Definition: pytypes.h:116
#define NAMESPACE_END(name)
Definition: detail/common.h:16
return_value_policy
Approach used to cast a previously unknown C++ instance into a Python object.
static handle cast(Func &&f_, return_value_policy policy, handle)
Definition: functional.h:85
typename std::conditional< B, T, F >::type conditional_t
detail::enable_if_t<!detail::move_never< T >::value, T > move(object &&obj)
Definition: cast.h:1685
handle release()
Definition: pytypes.h:247
Helper type to replace &#39;void&#39; in some expressions.
#define NAMESPACE_BEGIN(name)
Definition: detail/common.h:13
def capture(capsys)
Definition: conftest.py:111
#define PYBIND11_TYPE_CASTER(type, py_name)
Definition: cast.h:942
const handle & inc_ref() const &
Definition: pytypes.h:190
constexpr descr< 0 > concat()
Definition: descr.h:83