Treating bytearray the same as bytes in C modules

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
zpif
Posts: 10
Joined: Mon Jun 14, 2021 12:05 pm

Treating bytearray the same as bytes in C modules

Post by zpif » Tue Jul 06, 2021 11:04 am

Hi,

I have a C module with a function that handles bytes. I would like it to also transparently handle bytearrays. I can use mp_obj_is_str_or_bytes to determine if an mp_obj_t is of type "bytes", but this does not work if I pass a bytearray value to the function.

How do I find out if an mp_obj_t is of type "bytearray", and how do I get its contents?

Thank you,
Frank

zpif
Posts: 10
Joined: Mon Jun 14, 2021 12:05 pm

Re: Treating bytearray the same as bytes in C modules

Post by zpif » Tue Jul 06, 2021 11:43 am

Answering my own question, I guess I can use mp_get_buffer() regardless of whether the mp_obj_t is a string, bytes or bytearray object, right? I still won't know how to test whether an mp_obj_t is a bytearray, but I probably should not care.

User avatar
jimmo
Posts: 2754
Joined: Tue Aug 08, 2017 1:57 am
Location: Sydney, Australia
Contact:

Re: Treating bytearray the same as bytes in C modules

Post by jimmo » Wed Jul 07, 2021 12:37 am

zpif wrote:
Tue Jul 06, 2021 11:43 am
Answering my own question, I guess I can use mp_get_buffer() regardless of whether the mp_obj_t is a string, bytes or bytearray object, right? I still won't know how to test whether an mp_obj_t is a bytearray, but I probably should not care.
Yep, that's exactly right. Just ensure that you only set flags=MP_BUFFER_READ so you support read-only buffers too.

Post Reply