From df15e13ee74adbe7a654e7b6b3214595a96d955c Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Thu, 23 Feb 2017 16:48:47 -0500 Subject: [PATCH 1/2] Make string conversion stricter The string conversion logic added in PR #624 for all std::basic_strings was derived from the old std::wstring logic, but that was underused and turns out to have had a bug in accepting almost anything convertible to unicode, while the previous std::string logic was much stricter. This restores the previous std::string logic by only allowing actual unicode or string types. Fixes #685. --- include/pybind11/cast.h | 2 ++ tests/test_numpy_array.cpp | 5 +++++ tests/test_numpy_array.py | 8 ++++++++ 3 files changed, 15 insertions(+) diff --git a/include/pybind11/cast.h b/include/pybind11/cast.h index 01abf3f2c2..6cb02fd3a6 100644 --- a/include/pybind11/cast.h +++ b/include/pybind11/cast.h @@ -657,6 +657,8 @@ struct type_caster, enable_if_t(PyUnicode_FromObject(load_src.ptr())); if (!temp) { PyErr_Clear(); return false; } load_src = temp; diff --git a/tests/test_numpy_array.cpp b/tests/test_numpy_array.cpp index 14c4c29995..23da916951 100644 --- a/tests/test_numpy_array.cpp +++ b/tests/test_numpy_array.cpp @@ -150,4 +150,9 @@ test_initializer numpy_array([](py::module &m) { "array_t"_a=py::array_t(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"; }); }); diff --git a/tests/test_numpy_array.py b/tests/test_numpy_array.py index b96790c390..215b72e141 100644 --- a/tests/test_numpy_array.py +++ b/tests/test_numpy_array.py @@ -272,3 +272,11 @@ def test_constructors(): assert results["array"].dtype == np.int_ assert results["array_t"].dtype == np.int32 assert results["array_t"].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" From 1f86ce79ba8a69ea589dbd6aecfb38f0eb5dcd0a Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Thu, 23 Feb 2017 20:03:37 -0500 Subject: [PATCH 2/2] Added missing 'requires numpy' decorator (I forgot that the change to a global decorator here is in the not-yet-merged Eigen PR) --- tests/test_numpy_array.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/test_numpy_array.py b/tests/test_numpy_array.py index 215b72e141..25defe7d9f 100644 --- a/tests/test_numpy_array.py +++ b/tests/test_numpy_array.py @@ -274,6 +274,7 @@ def test_constructors(): assert results["array_t"].dtype == np.float64 +@pytest.requires_numpy def test_greedy_string_overload(): # issue 685 from pybind11_tests.array import issue685