Page 1 of 1

Simple MicroPython to C interface

Posted: Mon Jan 06, 2020 8:17 pm
by efr
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

Re: Simple MicroPython to C interface

Posted: Mon Jan 06, 2020 8:24 pm
by jimmo
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

Re: Simple MicroPython to C interface

Posted: Mon Jan 06, 2020 8:30 pm
by efr
Hi Jimmo,
Great, thank's for this useful information.
I will check this immediately ;-)
Regards
efr