Page 1 of 1

serialize memoryview

Posted: Mon Jan 18, 2021 3:19 am
by ttmetro
I'm working on an msgpack serializer for micropython written in C.

Python bytes objects map to the msgpack bin type and serializing those works fine.

Now I would like the packer also to handle memoryviews of bytes (and bytearray) objects and wonder how to do this. Memoryviews are defined in in py/objarray.[hc]. One option is to detect memoryviews with type BYTEARRAY_TYPECODE or MICROPY_PY_BUILTINS_BYTEARRAY and then directly access the mp_obj_array_t.

It this the correct approach or does a more appropriate api exist?

Re: serialize memoryview

Posted: Mon Jan 18, 2021 4:47 am
by jimmo
ttmetro wrote:
Mon Jan 18, 2021 3:19 am
It this the correct approach or does a more appropriate api exist?
When you serialise them, do you care about the distinction between memoryview and bytearray/bytes?

The reason I ask is that for any type, then if it's not something you directly handle (int, str, iterable), then calling mp_get_buffer will just give you back a buffer for any bytes-like type that you can directly serialise.

Re: serialize memoryview

Posted: Mon Jan 18, 2021 5:44 pm
by ttmetro
jimmo wrote:
Mon Jan 18, 2021 4:47 am
ttmetro wrote:
Mon Jan 18, 2021 3:19 am
It this the correct approach or does a more appropriate api exist?
... calling mp_get_buffer will just give you back a buffer for any bytes-like type that you can directly serialise.
Perfect! I'm glad I asked.
Stupidly, I already used mp_get_buffer, but restricted it to bytes only.