Home > OS >  How call python function from C in MicroPython
How call python function from C in MicroPython

Time:10-11

I have a function in my C-code and I want to call a python function that has been written in python script. Is it possible in MicroPython, if “yes” how can I do it? My C-Code Function:

float bar_C_Fun(int i, int j){
 return foo_Py_Fun(I,j);
 }

My Python-Code Function:

def  foo_Py_Fun(i , j):
  return i/j

I would be appreciate if someone help me about it

CodePudding user response:

Someone already asked this 4 years ago in another forum

The thread: https://forum.micropython.org/viewtopic.php?t=3761

The reply:

Re: How to call C function in python code

Post by dhylands » Wed Sep 06, 2017 10:44 pm You need to create a C module which exports functions which are callable from python.

See this thread here: https://forum.micropython.org/viewtopic.php?f=16&t=2861&p=19206#p19206 Dave Hylands

CodePudding user response:

While I haven't used MicroPython myself, from what I can see you have to do something as follows:

Sample function in test_python_file.py:

def test_python_function():
    return 10

C code:

int main(void)
{
    PyObject *name, *module, *func;

    Py_Initialize();
    PySys_SetPath("");

    name = PyString_FromString("test_python_file");
    module = PyImport_Import(name);
    func = PyObject_GetAttrString(module, "test_python_function");
    PYERR_IF(PyCallable_Check(func),
        PyObject *x = PyObject_CallObject(func, NULL);
        // PyLong_AsLong(x) will return value 10 as in test_python_file.py
        Py_DECREF(x);
    );

    Py_Finalize();

    return 0;
}
  • Related