Commit 819cb553 by Dean Moldovan

Fix nullptr to None conversion for builtin type casters

Fixes #731.

Generally, this applies to any caster made with PYBIND11_TYPE_CASTER().
parent dfd89a60
...@@ -469,6 +469,7 @@ public: ...@@ -469,6 +469,7 @@ public:
public: \ public: \
static PYBIND11_DESCR name() { return type_descr(py_name); } \ static PYBIND11_DESCR name() { return type_descr(py_name); } \
static handle cast(const type *src, return_value_policy policy, handle parent) { \ static handle cast(const type *src, return_value_policy policy, handle parent) { \
if (!src) return none().release(); \
return cast(*src, policy, parent); \ return cast(*src, policy, parent); \
} \ } \
operator type*() { return &value; } \ operator type*() { return &value; } \
......
...@@ -464,6 +464,12 @@ test_initializer python_types([](py::module &m) { ...@@ -464,6 +464,12 @@ test_initializer python_types([](py::module &m) {
m.def("ord_char16", [](char16_t c) -> uint16_t { return c; }); m.def("ord_char16", [](char16_t c) -> uint16_t { return c; });
m.def("ord_char32", [](char32_t c) -> uint32_t { return c; }); m.def("ord_char32", [](char32_t c) -> uint32_t { return c; });
m.def("ord_wchar", [](wchar_t c) -> int { return c; }); m.def("ord_wchar", [](wchar_t c) -> int { return c; });
m.def("return_none_string", []() -> std::string * { return nullptr; });
m.def("return_none_char", []() -> const char * { return nullptr; });
m.def("return_none_bool", []() -> bool * { return nullptr; });
m.def("return_none_int", []() -> int * { return nullptr; });
m.def("return_none_float", []() -> float * { return nullptr; });
}); });
#if defined(_MSC_VER) #if defined(_MSC_VER)
......
...@@ -501,3 +501,14 @@ def test_single_char_arguments(): ...@@ -501,3 +501,14 @@ def test_single_char_arguments():
with pytest.raises(ValueError) as excinfo: with pytest.raises(ValueError) as excinfo:
assert ord_wchar(u'aa') assert ord_wchar(u'aa')
assert str(excinfo.value) == toolong_message assert str(excinfo.value) == toolong_message
def test_builtins_cast_return_none():
"""Casters produced with PYBIND11_TYPE_CASTER() should convert nullptr to None"""
import pybind11_tests as m
assert m.return_none_string() is None
assert m.return_none_char() is None
assert m.return_none_bool() is None
assert m.return_none_int() is None
assert m.return_none_float() is None
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment