Question about call python function in C

C programming, build, interpreter/VM.
Target audience: MicroPython Developers.
Post Reply
Posts: 1
Joined: Tue Dec 17, 2019 8:43 am

Question about call python function in C

Post by errtiocv » Tue Dec 17, 2019 9:49 am

Hi, I'm trying on embedding micropython in C program.
I have a file:

Code: Select all

 def test(arg1,arg2):
    a = int(arg1)
    b = int(arg2)
    c= a+b
And I use mp_call_function_0 to call in C program:

Code: Select all

STATIC int do_file(const char *file) {
    nlr_buf_t nlr;
    if (nlr_push(&nlr) == 0) {
        // create lexer based on source kind
        mp_lexer_t *lex;
        lex = mp_lexer_new_from_file((const char*)file);
        qstr source_name = lex->source_name;
        mp_parse_tree_t parse_tree = mp_parse(lex, MP_PARSE_FILE_INPUT);
        mp_obj_t module_fun = mp_compile(&parse_tree, source_name, false);
        mp_obj_t ret = mp_call_function_0(module_fun);
        return 0;

    } else {
        // uncaught exception
        printf("uncaught exception\n");
        return (mp_obj_t)nlr.ret_val;
Then I call do_file("path/") in main function, it work well.

Now I want to call python file with input parameters and get the result return, I have tried mp_call_function_2(module_fun,mp_obj_new_int(arg1),mp_obj_new_int(arg2)) but it go uncaught exception.
And I don't know how to let C program recognize the function defined in the python file, is there any example?

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

Re: Question about call python function in C

Post by jimmo » Tue Dec 17, 2019 10:34 pm

What does it mean to call a python file with input parameters?

If what you want is to load your python file and then call individual functions from inside it (i.e. call the test function directly) then you'll need to lookup the test function in globals and execute it.

Look at runtime.c:mp_parse_compile_execute for the code path that handles this for the import statement.

The key detail though is that mp_compile returns a function that when executed will run all the top-level code in the file and assign all variables and defs into the current globals dict. In your example, the last line also calls the test function.

So if you want to capture just the variables from the file without modifying the current globals, you need to temporarily replace the globals dict with your own one.

But the simple answer to your question is you can lookup "test" in globals and find your function, then execute it the way you suggested using call_function_2

Post Reply