Skip to content

Modified Vector STL bind initialization from a buffer type with optimization for simple arrays #2298

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Aug 13, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions include/pybind11/stl_bind.h
Original file line number Diff line number Diff line change
Expand Up @@ -397,14 +397,19 @@ vector_buffer(Class_& cl) {
if (!detail::compare_buffer_info<T>::compare(info) || (ssize_t) sizeof(T) != info.itemsize)
throw type_error("Format mismatch (Python: " + info.format + " C++: " + format_descriptor<T>::format() + ")");

auto vec = std::unique_ptr<Vector>(new Vector());
vec->reserve((size_t) info.shape[0]);
T *p = static_cast<T*>(info.ptr);
ssize_t step = info.strides[0] / static_cast<ssize_t>(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;
Expand Down
9 changes: 9 additions & 0 deletions tests/test_stl_binders.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,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)
Expand Down Expand Up @@ -118,6 +123,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
Expand Down