Wenzel Jakob | 281aa0e | 2015-07-30 15:29:00 +0200 | [diff] [blame] | 1 | /* |
| 2 | pybind/functional.h: std::function<> support |
| 3 | |
| 4 | Copyright (c) 2015 Wenzel Jakob <wenzel@inf.ethz.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 <pybind/pybind.h> |
| 13 | #include <functional> |
| 14 | |
| 15 | NAMESPACE_BEGIN(pybind) |
| 16 | NAMESPACE_BEGIN(detail) |
| 17 | |
| 18 | template <typename Return, typename... Args> struct type_caster<std::function<Return(Args...)>> { |
| 19 | typedef std::function<Return(Args...)> type; |
| 20 | public: |
| 21 | |
| 22 | bool load(PyObject *src_, bool) { |
| 23 | if (!PyFunction_Check(src_)) |
| 24 | return false; |
| 25 | object src(src_, true); |
| 26 | value = [src](Args... args) -> Return { |
| 27 | object retval(pybind::handle(src).call<Args...>(std::move(args)...)); |
| 28 | /* Visual studio 2015 parser issue: need parentheses around this expression */ |
| 29 | return (retval.template cast<Return>()); |
| 30 | }; |
| 31 | return true; |
| 32 | } |
| 33 | |
| 34 | template <typename Func> |
| 35 | static PyObject *cast(Func &&f_, return_value_policy policy, PyObject *) { |
| 36 | cpp_function f(std::forward<Func>(f_), policy); |
| 37 | f.inc_ref(); |
| 38 | return f.ptr(); |
| 39 | } |
| 40 | |
Wenzel Jakob | f5fae92 | 2015-08-24 15:31:24 +0200 | [diff] [blame^] | 41 | |
| 42 | PYBIND_TYPE_CASTER(type, detail::descr("function<") + |
| 43 | type_caster<std::tuple<Args...>>::descr() + detail::descr(" -> ") + |
| 44 | type_caster<typename decay<Return>::type>::descr() + |
| 45 | detail::descr(">")); |
Wenzel Jakob | 281aa0e | 2015-07-30 15:29:00 +0200 | [diff] [blame] | 46 | }; |
| 47 | |
| 48 | NAMESPACE_END(detail) |
| 49 | NAMESPACE_END(pybind) |