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
This commit is contained in:
Yannick Jadoul 2017-05-29 03:13:55 +02:00 committed by Dean Moldovan
parent 427e4afc69
commit b700c5d672
2 changed files with 14 additions and 3 deletions

View File

@ -35,9 +35,17 @@ struct buffer_info {
size *= shape[i];
}
template <typename T>
buffer_info(T *ptr, detail::any_container<ssize_t> shape_in, detail::any_container<ssize_t> strides_in)
: 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)) { }
buffer_info(void *ptr, ssize_t itemsize, const std::string &format, ssize_t size)
: buffer_info(ptr, itemsize, format, 1, {size}, {itemsize}) { }
template <typename T>
buffer_info(T *ptr, ssize_t size)
: buffer_info(ptr, sizeof(T), format_descriptor<T>::format(), size) { }
explicit buffer_info(Py_buffer *view, bool ownview = true)
: buffer_info(view->buf, view->itemsize, view->format, view->ndim,
{view->shape, view->shape + view->ndim}, {view->strides, view->strides + view->ndim}) {
@ -70,6 +78,12 @@ struct buffer_info {
}
private:
struct private_ctr_tag { };
buffer_info(private_ctr_tag, void *ptr, ssize_t itemsize, const std::string &format, ssize_t ndim,
detail::any_container<ssize_t> &&shape_in, detail::any_container<ssize_t> &&strides_in)
: buffer_info(ptr, itemsize, format, ndim, std::move(shape_in), std::move(strides_in)) { }
Py_buffer *view = nullptr;
bool ownview = false;
};

View File

@ -136,9 +136,6 @@ test_initializer buffers([](py::module &m) {
.def_buffer([](Matrix &m) -> py::buffer_info {
return py::buffer_info(
m.data(), /* Pointer to buffer */
sizeof(float), /* Size of one scalar */
py::format_descriptor<float>::format(), /* Python struct-style format descriptor */
2, /* Number of dimensions */
{ m.rows(), m.cols() }, /* Buffer dimensions */
{ sizeof(float) * size_t(m.rows()), /* Strides (in bytes) for each index */
sizeof(float) }