Skip to content

Commit eb7c0b8

Browse files
author
Wenzel Jakob
committed
functional.h: support more kinds of Python functions
1 parent 3ee91b2 commit eb7c0b8

File tree

2 files changed

+16
-11
lines changed

2 files changed

+16
-11
lines changed

include/pybind11/functional.h

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,8 @@ template <typename Return, typename... Args> struct type_caster<std::function<Re
2020
public:
2121

2222
bool load(PyObject *src_, bool) {
23-
if (!PyFunction_Check(src_))
23+
src_ = detail::get_function(src_);
24+
if (!src_ || !(PyFunction_Check(src_) || PyCFunction_Check(src_)))
2425
return false;
2526
object src(src_, true);
2627
value = [src](Args... args) -> Return {

include/pybind11/pytypes.h

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,18 @@ class iterator : public object {
9494
};
9595

9696
NAMESPACE_BEGIN(detail)
97+
inline PyObject *get_function(PyObject *value) {
98+
if (value == nullptr)
99+
return nullptr;
100+
#if PY_MAJOR_VERSION >= 3
101+
if (PyInstanceMethod_Check(value))
102+
value = PyInstanceMethod_GET_FUNCTION(value);
103+
#endif
104+
if (PyMethod_Check(value))
105+
value = PyMethod_GET_FUNCTION(value);
106+
return value;
107+
}
108+
97109
class accessor {
98110
public:
99111
accessor(PyObject *obj, PyObject *key, bool attr)
@@ -346,16 +358,8 @@ class function : public object {
346358
PYBIND11_OBJECT_DEFAULT(function, object, PyFunction_Check)
347359

348360
bool is_cpp_function() {
349-
PyObject *ptr = m_ptr;
350-
if (ptr == nullptr)
351-
return false;
352-
#if PY_MAJOR_VERSION >= 3
353-
if (PyInstanceMethod_Check(ptr))
354-
ptr = PyInstanceMethod_GET_FUNCTION(ptr);
355-
#endif
356-
if (PyMethod_Check(ptr))
357-
ptr = PyMethod_GET_FUNCTION(ptr);
358-
return PyCFunction_Check(ptr);
361+
PyObject *ptr = detail::get_function(m_ptr);
362+
return ptr != nullptr && PyCFunction_Check(ptr);
359363
}
360364
};
361365

0 commit comments

Comments
 (0)