test_buffers.cpp 7.9 KB

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