Browse Source

python: make ArrayView properly convertible from Python array.

Also fix element sizes that aren't 1.
pull/1/head
Vladimír Vondruš 7 years ago
parent
commit
2ae83a0c26
  1. 9
      src/python/corrade/containers.cpp
  2. 7
      src/python/corrade/test/test_containers.py
  3. 5
      src/python/magnum/test/test_gl_gl.py

9
src/python/corrade/containers.cpp

@ -24,6 +24,7 @@
*/
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h> /* so ArrayView is convertible from python array */
#include <Corrade/Containers/Array.h>
#include <Corrade/Utility/FormatStl.h>
@ -70,15 +71,13 @@ template<class T> void arrayView(py::class_<PyArrayView<T>>& c) {
.def(py::init([](py::buffer buffer) {
py::buffer_info info = buffer.request(!std::is_const<T>::value);
// TODO: test for items that are not 1 byte size
if(info.ndim != 1)
throw py::buffer_error{Utility::formatString("expected one dimension but got {}", info.ndim)};
if(info.strides[0] != 1)
throw py::buffer_error{Utility::formatString("expected stride of 1 but got {}", info.strides[0])};
if(info.strides[0] != info.itemsize)
throw py::buffer_error{Utility::formatString("expected stride of {} but got {}", info.itemsize, info.strides[0])};
// TODO: need to take buffer.obj, not buffer!
return PyArrayView<T>{{static_cast<T*>(info.ptr), std::size_t(info.shape[0])}, buffer};
return PyArrayView<T>{{static_cast<T*>(info.ptr), std::size_t(info.shape[0]*info.itemsize)}, buffer};
}), "Construct from a buffer")
.def_buffer([](const PyArrayView<T>& self) -> py::buffer_info {
return py::buffer_info{

7
src/python/corrade/test/test_containers.py

@ -23,6 +23,7 @@
# DEALINGS IN THE SOFTWARE.
#
import array
import sys
import unittest
@ -72,6 +73,12 @@ class ArrayView(unittest.TestCase):
self.assertEqual(b[4], '!')
self.assertEqual(bytes(b), b'hell!')
def test_init_array(self):
a = array.array('f', [1.0, 4.5, 7.9])
b = containers.ArrayView(a)
self.assertIs(b.obj, a)
self.assertEqual(len(b), 3*4)
def test_init_buffer_unexpected_dimensions(self):
a = memoryview(b'123456').cast('b', shape=[2, 3])
self.assertEqual(bytes(a), b'123456')

5
src/python/magnum/test/test_gl_gl.py

@ -23,6 +23,7 @@
# DEALINGS IN THE SOFTWARE.
#
import array
import sys
import unittest
@ -47,6 +48,10 @@ class Buffer(GLTestCase):
a = gl.Buffer()
a.set_data(b'hello', gl.BufferUsage.STATIC_DRAW)
def test_set_data_array(self):
a = gl.Buffer()
a.set_data(array.array('f', [0.5, 1.2]))
class DefaultFramebuffer(GLTestCase):
def test(self):
# Using it should not crash, leak or cause double-free issues

Loading…
Cancel
Save