micropython port micro:bit v2 : Please add item assignment / referencing to global static memory blocks via bytearray() and memoryview() #13185
-
For the micropython port to the micro:bit v2, please consider adding item assignment / referencing to bytearray() memoryview() for memory blocks that have been instantiated with a global focus for the purpose of using the memory block as a static byte buffer. In other words, allow the ability to peek and poke one or more bytes to a block of memory that, once declared, is not moved by other operations. _global_ba = bytearray(64) _global_ba[:] = b'message payload' ... this is not supported _global_ba.extend(b'message payload') ... this moves the memory block and the pointer _mv_global_ba is now invalid |
Beta Was this translation helpful? Give feedback.
Replies: 6 comments 18 replies
-
I don't understand each and every python construct, but here are my thoughts about this (someone else please correct me when I got something wrong). The operations you would like to use are also not supported in standard python 3:
The last of your use cases (
|
Beta Was this translation helpful? Give feedback.
-
This is not valid Python: you can't do this in CPython. This is how to do it: _global_ba = bytearray(64)
_mv_global_ba = memoryview(_global_ba)
msg = b"My message"
_mv_global_ba[0: len(msg)] = msg |
Beta Was this translation helpful? Give feedback.
-
I'm not sure why it would matter if the block of memory gets moved? Is it for speed, or you don't have enough spare ram for copies to succeed? Explaining the problems you're seeing help others come up with the best suggestions! Regardless, I think you could get what you need with uctypes https://docs.micropython.org/en/latest/library/uctypes.html |
Beta Was this translation helpful? Give feedback.
-
FYI we are considering adding some sort of CPython does have |
Beta Was this translation helpful? Give feedback.
-
Yes, and the code I provided does exactly that. If you write buf = bytearray(100)
mvb = memoryview(buf) You can peek and poke via a = mvb[42] # Read from offset 42 (peek)
mvb[20] = 5 # Poke offset 20
msg = b"Here is a message"
mvb[50 : 50 + len(msg)] = msg # Put the message in locations starting at 50 Python uses this mechanism in place of pointers. |
Beta Was this translation helpful? Give feedback.
-
@rkompass See https://docs.micropython.org/en/latest/reference/asm_thumb2_str.html
This works for me on the standard micro:bit v2 firmware:
|
Beta Was this translation helpful? Give feedback.
micro:bit help desk reached out to me to let me know what was not supported and what was supported as follows: