blob: 1979dea7d2fec3a83655a2436d4277d043769de4 [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
41 PYBIND_TYPE_CASTER(type, "function<" + type_caster<std::tuple<Args...>>::name() + " -> " + type_caster<typename decay<Return>::type>::name() + ">");
42};
43
44NAMESPACE_END(detail)
45NAMESPACE_END(pybind)