From a7e62e1ca621c7a7c1b8956873a16c255f2939b6 Mon Sep 17 00:00:00 2001 From: Ivan Smirnov Date: Sun, 19 Jun 2016 14:37:55 +0100 Subject: [PATCH] Add buffer_info::as_pybuffer() method --- include/pybind11/common.h | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/include/pybind11/common.h b/include/pybind11/common.h index 0b2092920..d10535078 100644 --- a/include/pybind11/common.h +++ b/include/pybind11/common.h @@ -231,6 +231,31 @@ struct buffer_info { ~buffer_info() { if (view) { PyBuffer_Release(view); delete view; } } + + Py_buffer& as_pybuffer() const { + static Py_buffer buf { }; + // Py_buffer uses signed sizes, strides and shape!.. + static std::vector py_strides { }; + static std::vector py_shape { }; + buf.buf = ptr; + buf.itemsize = (Py_ssize_t) itemsize; + buf.format = const_cast(format.c_str()); + buf.ndim = (int) ndim; + buf.len = (Py_ssize_t) size; + py_strides.clear(); + py_shape.clear(); + for (size_t i = 0; i < ndim; ++i) { + py_strides.push_back((Py_ssize_t) strides[i]); + py_shape.push_back((Py_ssize_t) shape[i]); + } + buf.strides = py_strides.data(); + buf.shape = py_shape.data(); + buf.suboffsets = nullptr; + buf.readonly = false; + buf.internal = nullptr; + return buf; + } + private: Py_buffer *view = nullptr; };