Calling a python function from C

C programming, build, interpreter/VM.
Target audience: MicroPython Developers.
stijn
Posts: 335
Joined: Thu Apr 24, 2014 9:13 am

Re: Calling a python function from C

Post by stijn » Sun Mar 04, 2018 9:29 am

lists in python can be created from any iterable, and list is an iterable itself. In other words: use the constructor functionality to copy a list just like you would in Python, i.e. use mp_obj_new_list or whatever it's called. Likely that is exactly what list_copy does as well, didn't check.

jickster
Posts: 629
Joined: Thu Sep 07, 2017 8:57 pm

Re: Calling a python function from C

Post by jickster » Sun Mar 04, 2018 7:16 pm

stijn wrote:
Sun Mar 04, 2018 9:29 am
lists in python can be created from any iterable, and list is an iterable itself. In other words: use the constructor functionality to copy a list just like you would in Python, i.e. use mp_obj_new_list or whatever it's called. Likely that is exactly what list_copy does as well, didn't check.
I'd have to do

Code: Select all

mp_type_list.make_new(NULL, 1, 0, &my_list);
The first 3 args are still superfluous

stijn
Posts: 335
Joined: Thu Apr 24, 2014 9:13 am

Re: Calling a python function from C

Post by stijn » Sun Mar 04, 2018 8:19 pm

You sure? I'm 99% sure you could do something like my_list_copy = mp_obj_new_list(my_list->len, my_list->items);
Last edited by stijn on Sun Mar 04, 2018 8:21 pm, edited 1 time in total.

jickster
Posts: 629
Joined: Thu Sep 07, 2017 8:57 pm

Re: Calling a python function from C

Post by jickster » Sun Mar 04, 2018 8:21 pm

stijn wrote:
Sun Mar 04, 2018 8:19 pm
You sure? I don't have time to check but I'm 99% sure you could do something like my_list_copy = mp_obj_new_list(my_list->len, my_list->items);
It doesn't make a copy of the items. So if you use this function, the "items" will be shared between the two lists.

Code: Select all

mp_obj_t mp_obj_new_list(size_t n, mp_obj_t *items) {
    mp_obj_list_t *o = list_new(n);
    if (items != NULL) {
        for (size_t i = 0; i < n; i++) {
            o->items[i] = items[i];
        }
    }
    return MP_OBJ_FROM_PTR(o);
}
This actually reveals the utility of adding "mp_obj_make_new(mp_obj_t)" to make a copy of any mp_obj_t

stijn
Posts: 335
Joined: Thu Apr 24, 2014 9:13 am

Re: Calling a python function from C

Post by stijn » Mon Mar 05, 2018 9:03 am

What you want is called 'deepcopy'. Which is also exactly what the functionality is called in CPython. In general I'd say it's better to avoid that all together though, if you can. Maybe you should rethink your design. Having an attr function which makes deepcopies doesn't follow the 'principle of least surprise' at all.

Post Reply