blob: 1eedab67fcac27f4e920e64fc4101c920ee685ba [file] [log] [blame]
Wenzel Jakob281aa0e2015-07-30 15:29:00 +02001/*
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
15NAMESPACE_BEGIN(pybind)
16NAMESPACE_BEGIN(detail)
17
18template <typename Return, typename... Args> struct type_caster<std::function<Return(Args...)>> {
19 typedef std::function<Return(Args...)> type;
20public:
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 Jakobf5fae922015-08-24 15:31:24 +020041
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 Jakob281aa0e2015-07-30 15:29:00 +020046};
47
48NAMESPACE_END(detail)
49NAMESPACE_END(pybind)