diff --git a/include/pybind11/stl_bind.h b/include/pybind11/stl_bind.h index 61b94b62..47368f02 100644 --- a/include/pybind11/stl_bind.h +++ b/include/pybind11/stl_bind.h @@ -397,14 +397,19 @@ vector_buffer(Class_& cl) { if (!detail::compare_buffer_info::compare(info) || (ssize_t) sizeof(T) != info.itemsize) throw type_error("Format mismatch (Python: " + info.format + " C++: " + format_descriptor::format() + ")"); - auto vec = std::unique_ptr(new Vector()); - vec->reserve((size_t) info.shape[0]); T *p = static_cast(info.ptr); ssize_t step = info.strides[0] / static_cast(sizeof(T)); T *end = p + info.shape[0] * step; - for (; p != end; p += step) - vec->push_back(*p); - return vec.release(); + if (step == 1) { + return Vector(p, end); + } + else { + Vector vec; + vec.reserve((size_t) info.shape[0]); + for (; p != end; p += step) + vec.push_back(*p); + return vec; + } })); return; diff --git a/tests/test_stl_binders.py b/tests/test_stl_binders.py index 27b326f0..baa0f4e7 100644 --- a/tests/test_stl_binders.py +++ b/tests/test_stl_binders.py @@ -85,6 +85,11 @@ def test_vector_buffer(): mv[2] = '\x06' assert v[2] == 6 + if sys.version_info.major > 2: + mv = memoryview(b) + v = m.VectorUChar(mv[::2]) + assert v[1] == 3 + with pytest.raises(RuntimeError) as excinfo: m.create_undeclstruct() # Undeclared struct contents, no buffer interface assert "NumPy type info missing for " in str(excinfo.value) @@ -119,6 +124,10 @@ def test_vector_buffer_numpy(): ('y', 'float64'), ('z', 'bool')], align=True))) assert len(v) == 3 + b = np.array([1, 2, 3, 4], dtype=np.uint8) + v = m.VectorUChar(b[::2]) + assert v[1] == 3 + def test_vector_bool(): import pybind11_cross_module_tests as cm