Need Help with input parameters format and C function

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
hinay
Posts: 1
Joined: Thu Jan 09, 2020 7:47 pm

Need Help with input parameters format and C function

Post by hinay » Thu Jan 09, 2020 7:52 pm

Hi team,
I am relatively new to micropython and am struggling a bit trying to do the following. I have a series of functions implemented in C, which look like:

Code: Select all

void foo(double [] arg1, double [] arg2, double [] arg3)
I would like to create a micropython module that allows me to call such c function from the main .py that is running on an ESP32-based platform. So far, I have created such modules, including methods that allow calling such c functions. For example:

Code: Select all

STATIC mp_obj_t mymod_foo(size_t n_args, const mp_obj_t *args) {

mp_obj_t *arg1, *arg2, *arg3;
mp_uint_t len_arg1, len_arg1, len_arg3;
/* ToDo*/
return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mymod_obj, 4, 4, mymod_foo);
What I don't know is how to get double-type objects such that I can call the C-function foo(arg1, arg2, arg3). So far, I have tried things like:

Code: Select all

mp_obj_list_get(args[1], &len_arg1, &arg1);
which as expected copies whichever input list I have in args[1] in arg1 as well as extracts the length of such list. Nonetheless, what could I do next? How could I convert arg1 into a double-type array? Or is any other approach to do this?

Regards,
Hinay

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

Re: Need Help with input parameters format and C function

Post by jimmo » Fri Jan 10, 2020 12:16 am

Everything in MicroPython is an mp_obj_t. So your list will be a list of mp_obj_t.

So you need a way to convert your list of mp_obj_t to a contiguous array of double.

On most ports, MicroPython uses float for all floating point (very few actually use double natively). So you're going to have to copy the data anyway.

An mp_obj_t is a kind of hybrid type, depending on the bit pattern it can either be a small integer, a QSTR, a pointer, and on some ports, a float. On other ports, floats are handled as a pointer to a float object type.

Look at mpconfig.h for a description of how mp_obj_t works (and check your port to see what obj_repr it's using).

So yeah, you're likely going to have to write a loop to convert each mp_obj_t into a double and copy that into an array that you've allocated (either on the stack or on the gc heap).

You might also want to look at the "array" type which has built-in support for generating memory representations (i.e. array of double).

Post Reply