calling python function in C
Posted: Tue Apr 28, 2020 5:35 am
Hi all,
I would like to ask, whether it is possible to call a function that was defined in python at the C level. Here is the context: in ulab, the functions of the micropython math module are vectorised, i.e., one can do
and the function in b = vector.sin(a) is called exactly once in python, and the iteration is done in C.
How could one extend this idea to user-defined functions, like so:
This would be especially interesting for non-linear curve fitting and root finding.
I know that I could do something like this:
but that is not ideal, because fun wants to have arguments of mp_obj_t type, and returns values of mp_obj_t type, i.e., one has to convert to and from mp_obj_t, and this would not be much better than the simple list comprehension
Is there a way to save the round trip to mp_obj_t?
Thanks,
Zoltán
I would like to ask, whether it is possible to call a function that was defined in python at the C level. Here is the context: in ulab, the functions of the micropython math module are vectorised, i.e., one can do
Code: Select all
import ulab
from ulab import vector
a = ulab.array([1, 2, 3, 4])
b = vector.sin(a)
How could one extend this idea to user-defined functions, like so:
Code: Select all
import ulab
from ulab import vector
def f(x):
return sin(x) + x*x
a = ulab.array([1, 2, 3, 4])
b = f(a)
I know that I could do something like this:
Code: Select all
...
mp_call_fun_t fun = MICROPY_MAKE_POINTER_CALLABLE((void *)user_function->bytecode);
mp_float_t *array = (mp_float_t *)input_array->array->items;
for(size_t i=0; i < input_array->array->len; i++) {
mp_obj_t arg = mp_obj_new_float(*array++);
mp_obj_t results = fun(arg);
mp_float_t f_result = mp_obj_get_float(result);
...
}
...
Code: Select all
[f(x) for x in input_array]
Thanks,
Zoltán