1 /*
2 tests/test_buffers.cpp -- supporting Pythons' buffer protocol
3
4 Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
5
6 All rights reserved. Use of this source code is governed by a
7 BSD-style license that can be found in the LICENSE file.
8 */
9
10 #include "pybind11_tests.h"
11 #include "constructor_stats.h"
12 #include <pybind11/stl.h>
13
TEST_SUBMODULE(buffers,m)14 TEST_SUBMODULE(buffers, m) {
15 // test_from_python / test_to_python:
16 class Matrix {
17 public:
18 Matrix(py::ssize_t rows, py::ssize_t cols) : m_rows(rows), m_cols(cols) {
19 print_created(this, std::to_string(m_rows) + "x" + std::to_string(m_cols) + " matrix");
20 m_data = new float[(size_t) (rows*cols)];
21 memset(m_data, 0, sizeof(float) * (size_t) (rows * cols));
22 }
23
24 Matrix(const Matrix &s) : m_rows(s.m_rows), m_cols(s.m_cols) {
25 print_copy_created(this, std::to_string(m_rows) + "x" + std::to_string(m_cols) + " matrix");
26 m_data = new float[(size_t) (m_rows * m_cols)];
27 memcpy(m_data, s.m_data, sizeof(float) * (size_t) (m_rows * m_cols));
28 }
29
30 Matrix(Matrix &&s) : m_rows(s.m_rows), m_cols(s.m_cols), m_data(s.m_data) {
31 print_move_created(this);
32 s.m_rows = 0;
33 s.m_cols = 0;
34 s.m_data = nullptr;
35 }
36
37 ~Matrix() {
38 print_destroyed(this, std::to_string(m_rows) + "x" + std::to_string(m_cols) + " matrix");
39 delete[] m_data;
40 }
41
42 Matrix &operator=(const Matrix &s) {
43 print_copy_assigned(this, std::to_string(m_rows) + "x" + std::to_string(m_cols) + " matrix");
44 delete[] m_data;
45 m_rows = s.m_rows;
46 m_cols = s.m_cols;
47 m_data = new float[(size_t) (m_rows * m_cols)];
48 memcpy(m_data, s.m_data, sizeof(float) * (size_t) (m_rows * m_cols));
49 return *this;
50 }
51
52 Matrix &operator=(Matrix &&s) {
53 print_move_assigned(this, std::to_string(m_rows) + "x" + std::to_string(m_cols) + " matrix");
54 if (&s != this) {
55 delete[] m_data;
56 m_rows = s.m_rows; m_cols = s.m_cols; m_data = s.m_data;
57 s.m_rows = 0; s.m_cols = 0; s.m_data = nullptr;
58 }
59 return *this;
60 }
61
62 float operator()(py::ssize_t i, py::ssize_t j) const {
63 return m_data[(size_t) (i*m_cols + j)];
64 }
65
66 float &operator()(py::ssize_t i, py::ssize_t j) {
67 return m_data[(size_t) (i*m_cols + j)];
68 }
69
70 float *data() { return m_data; }
71
72 py::ssize_t rows() const { return m_rows; }
73 py::ssize_t cols() const { return m_cols; }
74 private:
75 py::ssize_t m_rows;
76 py::ssize_t m_cols;
77 float *m_data;
78 };
79 py::class_<Matrix>(m, "Matrix", py::buffer_protocol())
80 .def(py::init<py::ssize_t, py::ssize_t>())
81 /// Construct from a buffer
82 .def(py::init([](py::buffer const b) {
83 py::buffer_info info = b.request();
84 if (info.format != py::format_descriptor<float>::format() || info.ndim != 2)
85 throw std::runtime_error("Incompatible buffer format!");
86
87 auto v = new Matrix(info.shape[0], info.shape[1]);
88 memcpy(v->data(), info.ptr, sizeof(float) * (size_t) (v->rows() * v->cols()));
89 return v;
90 }))
91
92 .def("rows", &Matrix::rows)
93 .def("cols", &Matrix::cols)
94
95 /// Bare bones interface
96 .def("__getitem__", [](const Matrix &m, std::pair<py::ssize_t, py::ssize_t> i) {
97 if (i.first >= m.rows() || i.second >= m.cols())
98 throw py::index_error();
99 return m(i.first, i.second);
100 })
101 .def("__setitem__", [](Matrix &m, std::pair<py::ssize_t, py::ssize_t> i, float v) {
102 if (i.first >= m.rows() || i.second >= m.cols())
103 throw py::index_error();
104 m(i.first, i.second) = v;
105 })
106 /// Provide buffer access
107 .def_buffer([](Matrix &m) -> py::buffer_info {
108 return py::buffer_info(
109 m.data(), /* Pointer to buffer */
110 { m.rows(), m.cols() }, /* Buffer dimensions */
111 { sizeof(float) * size_t(m.cols()), /* Strides (in bytes) for each index */
112 sizeof(float) }
113 );
114 })
115 ;
116
117
118 // test_inherited_protocol
119 class SquareMatrix : public Matrix {
120 public:
121 SquareMatrix(py::ssize_t n) : Matrix(n, n) { }
122 };
123 // Derived classes inherit the buffer protocol and the buffer access function
124 py::class_<SquareMatrix, Matrix>(m, "SquareMatrix")
125 .def(py::init<py::ssize_t>());
126
127
128 // test_pointer_to_member_fn
129 // Tests that passing a pointer to member to the base class works in
130 // the derived class.
131 struct Buffer {
132 int32_t value = 0;
133
134 py::buffer_info get_buffer_info() {
135 return py::buffer_info(&value, sizeof(value),
136 py::format_descriptor<int32_t>::format(), 1);
137 }
138 };
139 py::class_<Buffer>(m, "Buffer", py::buffer_protocol())
140 .def(py::init<>())
141 .def_readwrite("value", &Buffer::value)
142 .def_buffer(&Buffer::get_buffer_info);
143
144
145 class ConstBuffer {
146 std::unique_ptr<int32_t> value;
147
148 public:
149 int32_t get_value() const { return *value; }
150 void set_value(int32_t v) { *value = v; }
151
152 py::buffer_info get_buffer_info() const {
153 return py::buffer_info(value.get(), sizeof(*value),
154 py::format_descriptor<int32_t>::format(), 1);
155 }
156
157 ConstBuffer() : value(new int32_t{0}) { };
158 };
159 py::class_<ConstBuffer>(m, "ConstBuffer", py::buffer_protocol())
160 .def(py::init<>())
161 .def_property("value", &ConstBuffer::get_value, &ConstBuffer::set_value)
162 .def_buffer(&ConstBuffer::get_buffer_info);
163
164 struct DerivedBuffer : public Buffer { };
165 py::class_<DerivedBuffer>(m, "DerivedBuffer", py::buffer_protocol())
166 .def(py::init<>())
167 .def_readwrite("value", (int32_t DerivedBuffer::*) &DerivedBuffer::value)
168 .def_buffer(&DerivedBuffer::get_buffer_info);
169
170 struct BufferReadOnly {
171 const uint8_t value = 0;
172 BufferReadOnly(uint8_t value): value(value) {}
173
174 py::buffer_info get_buffer_info() {
175 return py::buffer_info(&value, 1);
176 }
177 };
178 py::class_<BufferReadOnly>(m, "BufferReadOnly", py::buffer_protocol())
179 .def(py::init<uint8_t>())
180 .def_buffer(&BufferReadOnly::get_buffer_info);
181
182 struct BufferReadOnlySelect {
183 uint8_t value = 0;
184 bool readonly = false;
185
186 py::buffer_info get_buffer_info() {
187 return py::buffer_info(&value, 1, readonly);
188 }
189 };
190 py::class_<BufferReadOnlySelect>(m, "BufferReadOnlySelect", py::buffer_protocol())
191 .def(py::init<>())
192 .def_readwrite("value", &BufferReadOnlySelect::value)
193 .def_readwrite("readonly", &BufferReadOnlySelect::readonly)
194 .def_buffer(&BufferReadOnlySelect::get_buffer_info);
195
196 // Expose buffer_info for testing.
197 py::class_<py::buffer_info>(m, "buffer_info")
198 .def(py::init<>())
199 .def_readonly("itemsize", &py::buffer_info::itemsize)
200 .def_readonly("size", &py::buffer_info::size)
201 .def_readonly("format", &py::buffer_info::format)
202 .def_readonly("ndim", &py::buffer_info::ndim)
203 .def_readonly("shape", &py::buffer_info::shape)
204 .def_readonly("strides", &py::buffer_info::strides)
205 .def_readonly("readonly", &py::buffer_info::readonly)
206 .def("__repr__", [](py::handle self) {
207 return py::str("itemsize={0.itemsize!r}, size={0.size!r}, format={0.format!r}, ndim={0.ndim!r}, shape={0.shape!r}, strides={0.strides!r}, readonly={0.readonly!r}").format(self);
208 })
209 ;
210
211 m.def("get_buffer_info", [](py::buffer buffer) {
212 return buffer.request();
213 });
214 }
215