Missing `memoryview.cast` in MicroPython
It seems memoryview has no cast() method in MicroPython, has it?
Is there another way to create a memoryview out of an array.array('h', array_size) that results in a bytearray-like memory view without making a copy of the buffer?
In code, for better clarity:
import array
size = 64
a = array.array('h', range(size))
m = memoryview(a).cast('B')
assert len(m) == 2 * size
Inconsistent behavior comparing binary data to arrays
I'm got an application that deals with 16bit image data in a large binary array (1.2MB). It's typically held in a C object, but exposed via a raw buffer interface (memoryview etc).
For testing data content, I was previously doing something like
pattern = [0, 0, 1, 1, 2, 2, 4, 4, 8, 8, 16, 16, 32, 32, 64, 64, 128, 128,
256, 256, 512, 512, 1024, 1024, 2048, 2048, 4095, 4095]
pattern_arr = array.array('H', pattern) # 16 bit unsigned short array
assert memoryview(image)[0: len(pattern) * 2] == pattern_arr
Even though the memoryview will be exposed as a U8, the binary comparison to the array was fine.
Ever since py/objarray: Prohibit comparison of mismatching types. (https://github.com/micropython/micropython/commit/57365d855734142deb030ebcd00c10efcedf554b by @stinos) however this throws a NotImplementedError which I guess is the intent behind that commit? Somewhat annoying for me, but presumably safer?
However, while looking for a solution here (cast my image to U16 without copy?) I found:
image_row_bytes = uctypes.bytearray_at(uctypes.addressof(image), len(pattern) * 2)
assert image_row_bytes == pattern_arr
seems to work fine... so comparing to U16 array to memoryview is not allowed but U16 array compared to bytearray is allowed?
Is this intended?