diff --git a/example/example14.cpp b/example/example14.cpp index 5c6d918d..f7f176a1 100644 --- a/example/example14.cpp +++ b/example/example14.cpp @@ -1,5 +1,5 @@ /* - example/example14.cpp -- opaque types + example/example14.cpp -- opaque types, passing void pointers Copyright (c) 2015 Wenzel Jakob @@ -26,4 +26,7 @@ void init_ex14(py::module &m) { for (auto entry : l) std::cout << " " << entry << std::endl; }); + + m.def("return_void_ptr", []() { return (void *) 1234; }); + m.def("print_void_ptr", [](void *ptr) { std::cout << "Got void ptr : " << (uint64_t) ptr << std::endl; }); } diff --git a/example/example14.py b/example/example14.py index c9c86652..aef9923f 100644 --- a/example/example14.py +++ b/example/example14.py @@ -12,3 +12,7 @@ print_opaque_list(l) print("Back element is %s" % l.back()) l.pop_back() print_opaque_list(l) + +from example import return_void_ptr, print_void_ptr + +print_void_ptr(return_void_ptr()) diff --git a/example/example14.ref b/example/example14.ref index d738fefc..38a27e17 100644 --- a/example/example14.ref +++ b/example/example14.ref @@ -4,3 +4,4 @@ Opaque list: Back element is Element 2 Opaque list: Element 1 +Got void ptr : 1234 diff --git a/include/pybind11/cast.h b/include/pybind11/cast.h index 7f30fd29..7835561c 100644 --- a/include/pybind11/cast.h +++ b/include/pybind11/cast.h @@ -323,7 +323,26 @@ public: PYBIND11_TYPE_CASTER(void_type, _("NoneType")); }; -template <> class type_caster : public type_caster { }; +template <> class type_caster : public type_caster { +public: + using type_caster::cast; + + bool load(handle h, bool) { + capsule c(h, true); + if (!c.check()) + return false; + value = (void *) c; + return true; + } + + static handle cast(void *ptr, return_value_policy /* policy */, handle /* parent */) { + return capsule(ptr).inc_ref(); + } + operator void *() { return value; } +private: + void *value; +}; + template <> class type_caster : public type_caster { }; template <> class type_caster {