Skip to content

Commit

Permalink
Make string conversion stricter
Browse files Browse the repository at this point in the history
The string conversion logic added in PR pybind#624 for all std::basic_strings
was using the old std::wstring logic, but that was underused and turns
out to have hade a bug in accepting almost anything convertible to
the previous std::string logic by only accepting unicode or byte/string
(Python 3/2) types.

Fixes pybind#685.
  • Loading branch information
jagerman committed Feb 23, 2017
1 parent 2447088 commit 927a19f
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 0 deletions.
2 changes: 2 additions & 0 deletions include/pybind11/cast.h
Original file line number Diff line number Diff line change
Expand Up @@ -633,6 +633,8 @@ struct type_caster<std::basic_string<CharT, Traits, Allocator>, enable_if_t<is_s
if (!src) {
return false;
} else if (!PyUnicode_Check(load_src.ptr())) {
if (!PYBIND11_BYTES_CHECK(load_src.ptr()))
return false;
temp = reinterpret_steal<object>(PyUnicode_FromObject(load_src.ptr()));
if (!temp) { PyErr_Clear(); return false; }
load_src = temp;
Expand Down
5 changes: 5 additions & 0 deletions tests/test_numpy_array.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -150,4 +150,9 @@ test_initializer numpy_array([](py::module &m) {
"array_t<double>"_a=py::array_t<double>(o)
);
});

// Issue 685: ndarray shouldn't go to std::string overload
sm.def("issue685", [](std::string) { return "string"; });
sm.def("issue685", [](py::array) { return "array"; });
sm.def("issue685", [](py::object) { return "other"; });
});
8 changes: 8 additions & 0 deletions tests/test_numpy_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,3 +261,11 @@ def test_constructors():
assert results["array"].dtype == np.int_
assert results["array_t<int32>"].dtype == np.int32
assert results["array_t<double>"].dtype == np.float64


def test_greedy_string_overload(): # issue 685
from pybind11_tests.array import issue685

assert issue685("abc") == "string"
assert issue685(np.array([97, 98, 99], dtype='b')) == "array"
assert issue685(123) == "other"

0 comments on commit 927a19f

Please sign in to comment.