Skip to content

Commit 927a19f

Browse files
committed
Make string conversion stricter
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.
1 parent 2447088 commit 927a19f

File tree

3 files changed

+15
-0
lines changed

3 files changed

+15
-0
lines changed

include/pybind11/cast.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -633,6 +633,8 @@ struct type_caster<std::basic_string<CharT, Traits, Allocator>, enable_if_t<is_s
633633
if (!src) {
634634
return false;
635635
} else if (!PyUnicode_Check(load_src.ptr())) {
636+
if (!PYBIND11_BYTES_CHECK(load_src.ptr()))
637+
return false;
636638
temp = reinterpret_steal<object>(PyUnicode_FromObject(load_src.ptr()));
637639
if (!temp) { PyErr_Clear(); return false; }
638640
load_src = temp;

tests/test_numpy_array.cpp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,4 +150,9 @@ test_initializer numpy_array([](py::module &m) {
150150
"array_t<double>"_a=py::array_t<double>(o)
151151
);
152152
});
153+
154+
// Issue 685: ndarray shouldn't go to std::string overload
155+
sm.def("issue685", [](std::string) { return "string"; });
156+
sm.def("issue685", [](py::array) { return "array"; });
157+
sm.def("issue685", [](py::object) { return "other"; });
153158
});

tests/test_numpy_array.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,3 +261,11 @@ def test_constructors():
261261
assert results["array"].dtype == np.int_
262262
assert results["array_t<int32>"].dtype == np.int32
263263
assert results["array_t<double>"].dtype == np.float64
264+
265+
266+
def test_greedy_string_overload(): # issue 685
267+
from pybind11_tests.array import issue685
268+
269+
assert issue685("abc") == "string"
270+
assert issue685(np.array([97, 98, 99], dtype='b')) == "array"
271+
assert issue685(123) == "other"

0 commit comments

Comments
 (0)