You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

186 lines
6.3 KiB

  1. /*
  2. example/example6.cpp -- supporting Pythons' sequence protocol, iterators,
  3. etc.
  4. Copyright (c) 2015 Wenzel Jakob <wenzel@inf.ethz.ch>
  5. All rights reserved. Use of this source code is governed by a
  6. BSD-style license that can be found in the LICENSE file.
  7. */
  8. #include "example.h"
  9. #include <pybind11/operators.h>
  10. #include <pybind11/stl.h>
  11. class Sequence {
  12. public:
  13. Sequence(size_t size) : m_size(size) {
  14. std::cout << "Value constructor: Creating a sequence with " << m_size << " entries" << std::endl;
  15. m_data = new float[size];
  16. memset(m_data, 0, sizeof(float) * size);
  17. }
  18. Sequence(const std::vector<float> &value) : m_size(value.size()) {
  19. std::cout << "Value constructor: Creating a sequence with " << m_size << " entries" << std::endl;
  20. m_data = new float[m_size];
  21. memcpy(m_data, &value[0], sizeof(float) * m_size);
  22. }
  23. Sequence(const Sequence &s) : m_size(s.m_size) {
  24. std::cout << "Copy constructor: Creating a sequence with " << m_size << " entries" << std::endl;
  25. m_data = new float[m_size];
  26. memcpy(m_data, s.m_data, sizeof(float)*m_size);
  27. }
  28. Sequence(Sequence &&s) : m_size(s.m_size), m_data(s.m_data) {
  29. std::cout << "Move constructor: Creating a sequence with " << m_size << " entries" << std::endl;
  30. s.m_size = 0;
  31. s.m_data = nullptr;
  32. }
  33. ~Sequence() {
  34. std::cout << "Freeing a sequence with " << m_size << " entries" << std::endl;
  35. delete[] m_data;
  36. }
  37. Sequence &operator=(const Sequence &s) {
  38. std::cout << "Assignment operator: Creating a sequence with " << s.m_size << " entries" << std::endl;
  39. delete[] m_data;
  40. m_size = s.m_size;
  41. m_data = new float[m_size];
  42. memcpy(m_data, s.m_data, sizeof(float)*m_size);
  43. return *this;
  44. }
  45. Sequence &operator=(Sequence &&s) {
  46. std::cout << "Move assignment operator: Creating a sequence with " << s.m_size << " entries" << std::endl;
  47. if (&s != this) {
  48. delete[] m_data;
  49. m_size = s.m_size;
  50. m_data = s.m_data;
  51. s.m_size = 0;
  52. s.m_data = nullptr;
  53. }
  54. return *this;
  55. }
  56. bool operator==(const Sequence &s) const {
  57. if (m_size != s.size())
  58. return false;
  59. for (size_t i=0; i<m_size; ++i)
  60. if (m_data[i] != s[i])
  61. return false;
  62. return true;
  63. }
  64. bool operator!=(const Sequence &s) const {
  65. return !operator==(s);
  66. }
  67. float operator[](size_t index) const {
  68. return m_data[index];
  69. }
  70. float &operator[](size_t index) {
  71. return m_data[index];
  72. }
  73. bool contains(float v) const {
  74. for (size_t i=0; i<m_size; ++i)
  75. if (v == m_data[i])
  76. return true;
  77. return false;
  78. }
  79. Sequence reversed() const {
  80. Sequence result(m_size);
  81. for (size_t i=0; i<m_size; ++i)
  82. result[m_size-i-1] = m_data[i];
  83. return result;
  84. }
  85. size_t size() const { return m_size; }
  86. const float *begin() const { return m_data; }
  87. const float *end() const { return m_data+m_size; }
  88. private:
  89. size_t m_size;
  90. float *m_data;
  91. };
  92. void init_ex6(py::module &m) {
  93. py::class_<Sequence> seq(m, "Sequence");
  94. seq.def(py::init<size_t>())
  95. .def(py::init<const std::vector<float>&>())
  96. /// Bare bones interface
  97. .def("__getitem__", [](const Sequence &s, size_t i) {
  98. if (i >= s.size())
  99. throw py::index_error();
  100. return s[i];
  101. })
  102. .def("__setitem__", [](Sequence &s, size_t i, float v) {
  103. if (i >= s.size())
  104. throw py::index_error();
  105. s[i] = v;
  106. })
  107. .def("__len__", &Sequence::size)
  108. /// Optional sequence protocol operations
  109. .def("__iter__", [](const Sequence &s) { return py::make_iterator(s.begin(), s.end()); },
  110. py::keep_alive<0, 1>() /* Essential: keep object alive while iterator exists */)
  111. .def("__contains__", [](const Sequence &s, float v) { return s.contains(v); })
  112. .def("__reversed__", [](const Sequence &s) -> Sequence { return s.reversed(); })
  113. /// Slicing protocol (optional)
  114. .def("__getitem__", [](const Sequence &s, py::slice slice) -> Sequence* {
  115. py::ssize_t start, stop, step, slicelength;
  116. if (!slice.compute(s.size(), &start, &stop, &step, &slicelength))
  117. throw py::error_already_set();
  118. Sequence *seq = new Sequence(slicelength);
  119. for (int i=0; i<slicelength; ++i) {
  120. (*seq)[i] = s[start]; start += step;
  121. }
  122. return seq;
  123. })
  124. .def("__setitem__", [](Sequence &s, py::slice slice, const Sequence &value) {
  125. py::ssize_t start, stop, step, slicelength;
  126. if (!slice.compute(s.size(), &start, &stop, &step, &slicelength))
  127. throw py::error_already_set();
  128. if ((size_t) slicelength != value.size())
  129. throw std::runtime_error("Left and right hand size of slice assignment have different sizes!");
  130. for (int i=0; i<slicelength; ++i) {
  131. s[start] = value[i]; start += step;
  132. }
  133. })
  134. /// Comparisons
  135. .def(py::self == py::self)
  136. .def(py::self != py::self);
  137. // Could also define py::self + py::self for concatenation, etc.
  138. #if 0
  139. // Obsolete: special data structure for exposing custom iterator types to python
  140. // kept here for illustrative purposes because there might be some use cases which
  141. // are not covered by the much simpler py::make_iterator
  142. struct PySequenceIterator {
  143. PySequenceIterator(const Sequence &seq, py::object ref) : seq(seq), ref(ref) { }
  144. float next() {
  145. if (index == seq.size())
  146. throw py::stop_iteration();
  147. return seq[index++];
  148. }
  149. const Sequence &seq;
  150. py::object ref; // keep a reference
  151. size_t index = 0;
  152. };
  153. py::class_<PySequenceIterator>(seq, "Iterator")
  154. .def("__iter__", [](PySequenceIterator &it) -> PySequenceIterator& { return it; })
  155. .def("__next__", &PySequenceIterator::next);
  156. On the actual Sequence object, the iterator would be constructed as follows:
  157. .def("__iter__", [](py::object s) { return PySequenceIterator(s.cast<const Sequence &>(), s); })
  158. #endif
  159. }