Simple MicroPython to C interface

Discussion about programs, libraries and tools that work with MicroPython. Mostly these are provided by a third party.
Target audience: All users and developers of MicroPython.
Post Reply
efr
Posts: 2
Joined: Mon Jan 06, 2020 7:57 pm

Simple MicroPython to C interface

Post by efr » Mon Jan 06, 2020 8:17 pm

Hi,
I would like to write a C library for interfacing a micropyton command.
In C something like this (of course, the types are wrong ...)

...
STATIC mp_obj_t myLibrary_call(mp_obj_t array_obj) {
uint32_t i;

for (i = 0; i < 10; i++) {
array_obj = i;
}
}
...

In micropyton, something like this :

buffer = [0] * 10
print(buffer)
0 0 0 0 0 0 0 0 0 0

myLibrary.call(buffer)
print(buffer)
0 1 2 3 4 5 6 7 8 9

In the package I found some examples that use to pass simple integers (but no arrays).
Any suggestion to help me to write the C & micropython code for this simple array example?

Thank you
efr

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

Re: Simple MicroPython to C interface

Post by jimmo » Mon Jan 06, 2020 8:24 pm

In general, given an mp_obj_t you need to check its type and then convert it to the type you're expecting (e.g. MP_OBJ_TO_PTR).

But in this case, to extract the bytes out of any type supporting the buffer protocol, you want to use mp_get_buffer_raise() or similar:

Code: Select all

    mp_buffer_info_t bufinfo = {0};
    mp_get_buffer_raise(my_obj, &bufinfo, MP_BUFFER_READ);
    // Now you can use bufinfo.len  and  bufinfo.buf

efr
Posts: 2
Joined: Mon Jan 06, 2020 7:57 pm

Re: Simple MicroPython to C interface

Post by efr » Mon Jan 06, 2020 8:30 pm

Hi Jimmo,
Great, thank's for this useful information.
I will check this immediately ;-)
Regards
efr

Post Reply