I have a buffer (I obtain it as bytes through cffi
) for an column-major array.
Is there a way to obtain a memoryview for it with the correct attributes for Python's buffer protocol ? The method cast
lets me assign a new shape but does not appear to let one specify whether the view is row or column-major.
For example:
# Let b be my buffer of bytes for a column major array of integers
shape = (5, 2, 3)
mv = memoryview(b).cast('i', shape=shape)
# Expectedly not what I want as this is then assumed to be a
# C-style row-major array
mv.to_list()
There really is no easy way to change the strides/shape of a memoryview
without diving into C. The easiest way is to use NumPy (I create the buffer here, you should skip that line):
shape = (5, 2, 3)
b = bytearray('a' * np.dtype('i').itemsize * np.prod(shape))
a = np.frombuffer(b, dtype='i').reshape(shape)
a.strides = a.strides[::-1]
m = memoryview(a)
print(m.strides)