diff --git a/example/example-callbacks.cpp b/example/example-callbacks.cpp index afb864db..a5a3b833 100644 --- a/example/example-callbacks.cpp +++ b/example/example-callbacks.cpp @@ -38,7 +38,10 @@ py::cpp_function test_callback5() { int dummy_function(int i) { return i + 1; } int dummy_function2(int i, int j) { return i + j; } std::function roundtrip(std::function f) { - std::cout << "roundtrip.." << std::endl; + if (!f) + std::cout << "roundtrip (got None).." << std::endl; + else + std::cout << "roundtrip.." << std::endl; return f; } diff --git a/example/example-callbacks.py b/example/example-callbacks.py index 89f83a1b..68a485a7 100755 --- a/example/example-callbacks.py +++ b/example/example-callbacks.py @@ -68,6 +68,8 @@ from example import roundtrip test_dummy_function(dummy_function) test_dummy_function(roundtrip(dummy_function)) +if roundtrip(None) is not None: + print("Problem!") test_dummy_function(lambda x: x + 2) try: diff --git a/example/example-callbacks.ref b/example/example-callbacks.ref index 72f751a0..c6f8f531 100644 --- a/example/example-callbacks.ref +++ b/example/example-callbacks.ref @@ -30,6 +30,7 @@ Copy constructions: 1 Move constructions: True argument matches dummy_function eval(1) = 2 +roundtrip (got None).. roundtrip.. argument matches dummy_function eval(1) = 2 diff --git a/include/pybind11/functional.h b/include/pybind11/functional.h index e82e520e..0df8129c 100644 --- a/include/pybind11/functional.h +++ b/include/pybind11/functional.h @@ -20,6 +20,9 @@ template struct type_caster::value, void_type, Return>::type retval_type; public: bool load(handle src_, bool) { + if (src_.ptr() == Py_None) + return true; + src_ = detail::get_function(src_); if (!src_ || !PyCallable_Check(src_.ptr())) return false; @@ -58,6 +61,9 @@ public: template static handle cast(Func &&f_, return_value_policy policy, handle /* parent */) { + if (!f_) + return handle(Py_None).inc_ref(); + auto result = f_.template target(); if (result) return cpp_function(*result, policy).release();