Calling a python function from C

C programming, build, interpreter/VM.
Target audience: MicroPython Developers.
gshilling
Posts: 1
Joined: Mon Feb 02, 2015 11:32 pm

Calling a python function from C

Postby gshilling » Mon Feb 02, 2015 11:37 pm

I'm working on embedding micro python into another STM32 C application I have. I would like to be able to call functions in a python script file from the C application. Is there a call like PyObject_GetAttrString from CPython to get a pointer to a function that could then be feed into mp_call_function_n_kw?

User avatar
dhylands
Posts: 2264
Joined: Mon Jan 06, 2014 6:08 pm
Location: Shuswap, BC, Canada
Contact:

Re: Calling a python function from C

Postby dhylands » Tue Feb 03, 2015 2:28 am

Here's an example of calling a python function from C:
https://github.com/micropython/micropyt ... pin.c#L118

If you search for mp_call_function in the stmhal directory you'll see several other examples.

Damien
Site Admin
Posts: 505
Joined: Mon Dec 09, 2013 5:02 pm

Postby Damien » Tue Feb 03, 2015 6:31 pm

You might want to try mp_load_global to get a function (or other object) defined by a script.

Tetraeder
Posts: 43
Joined: Thu Mar 05, 2015 1:12 pm
Location: Germany

Re: Calling a python function from C

Postby Tetraeder » Tue Feb 07, 2017 1:59 pm

I have a similar question to the thread topic:
I create for pyboard the frozen script -> own.py

Code: Select all

def test():
   print('hello test')


I created in stmhal the folder "scripts" and define in Makefile the FROZEN_DIR. Copied the own.py script in folder scripts.
compile-> repl -> works, with

Code: Select all

>>> import own 
>>> own.test()
hello test
>>>


but how can I call this function for example in main.c by "soft reset".
I tried:

Code: Select all

mp_call_function_0(MP_STATE_PORT(own_test))

but no output via repl.
Maybe I don't understand the function :?:

User avatar
dhylands
Posts: 2264
Joined: Mon Jan 06, 2014 6:08 pm
Location: Shuswap, BC, Canada
Contact:

Re: Calling a python function from C

Postby dhylands » Tue Feb 07, 2017 5:33 pm

The real trick is that you need to register the function from python first so that C can get a pointer to the function.

Otherwise you need to import the module, and then dig the function out of the module, which is doable, just a bunch more code.

You could also do the equivalent to the do_str function in unix/main.c:
https://github.com/micropython/micropyt ... #L287-L290
and call:

Code: Select all

do_str("import own\nown.test()")
Disclaimer: I didn't actually test that.

boot.py and main.py both run as part of a soft-reset.

You need to ensure that you're calling it at the right place in main.c.
boot.py is run before USB is initialized. main.py is run after USB is initialized.


Return to “Development of MicroPython”

Who is online

Users browsing this forum: No registered users and 1 guest