Skip to content

Commit b700c5d

Browse files
YannickJadouldean0x7d
authored andcommitted
Convenience constructor templates for buffer_info (#860)
* Added template constructors to buffer_info that can deduce the item size, format string, and number of dimensions from the pointer type and the shape container * Implemented actual buffer_info constructor as private delegate constructor taking rvalue reference as a workaround for the evaluation order move problem on GCC 4.8
1 parent 427e4af commit b700c5d

File tree

2 files changed

+14
-3
lines changed

2 files changed

+14
-3
lines changed

include/pybind11/buffer_info.h

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,9 +35,17 @@ struct buffer_info {
3535
size *= shape[i];
3636
}
3737

38+
template <typename T>
39+
buffer_info(T *ptr, detail::any_container<ssize_t> shape_in, detail::any_container<ssize_t> strides_in)
40+
: buffer_info(private_ctr_tag(), ptr, sizeof(T), format_descriptor<T>::format(), static_cast<ssize_t>(shape_in->size()), std::move(shape_in), std::move(strides_in)) { }
41+
3842
buffer_info(void *ptr, ssize_t itemsize, const std::string &format, ssize_t size)
3943
: buffer_info(ptr, itemsize, format, 1, {size}, {itemsize}) { }
4044

45+
template <typename T>
46+
buffer_info(T *ptr, ssize_t size)
47+
: buffer_info(ptr, sizeof(T), format_descriptor<T>::format(), size) { }
48+
4149
explicit buffer_info(Py_buffer *view, bool ownview = true)
4250
: buffer_info(view->buf, view->itemsize, view->format, view->ndim,
4351
{view->shape, view->shape + view->ndim}, {view->strides, view->strides + view->ndim}) {
@@ -70,6 +78,12 @@ struct buffer_info {
7078
}
7179

7280
private:
81+
struct private_ctr_tag { };
82+
83+
buffer_info(private_ctr_tag, void *ptr, ssize_t itemsize, const std::string &format, ssize_t ndim,
84+
detail::any_container<ssize_t> &&shape_in, detail::any_container<ssize_t> &&strides_in)
85+
: buffer_info(ptr, itemsize, format, ndim, std::move(shape_in), std::move(strides_in)) { }
86+
7387
Py_buffer *view = nullptr;
7488
bool ownview = false;
7589
};

tests/test_buffers.cpp

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -136,9 +136,6 @@ test_initializer buffers([](py::module &m) {
136136
.def_buffer([](Matrix &m) -> py::buffer_info {
137137
return py::buffer_info(
138138
m.data(), /* Pointer to buffer */
139-
sizeof(float), /* Size of one scalar */
140-
py::format_descriptor<float>::format(), /* Python struct-style format descriptor */
141-
2, /* Number of dimensions */
142139
{ m.rows(), m.cols() }, /* Buffer dimensions */
143140
{ sizeof(float) * size_t(m.rows()), /* Strides (in bytes) for each index */
144141
sizeof(float) }

0 commit comments

Comments
 (0)