Skip to content Skip to sidebar Skip to footer

Embedding Python In C - Segfault

From reading another post, I am trying to embbed some some Python code into C: main.c #include int callModuleFunc(int array[], size_t size) { PyObject *mymodu

Solution 1:

There were several problems with your code:

  1. Py_Initialize() was not called.
  2. PyImport_ImportModule() failed to find your python file, since in embedded Python you start without an initial module, relative to which the search can work. The fix is to explicitly include the current directory in sys.path.
  3. "(O)" in Py_BuildValue() should use a capital 'O'.
  4. The printlist function should return a value (since that is what the C-code expects).

This should work:

main.c

#include<Python.h>voidinitPython(){
    Py_Initialize();
    PyObject *sysmodule = PyImport_ImportModule("sys");
    PyObject *syspath = PyObject_GetAttrString(sysmodule, "path");
    PyList_Append(syspath, PyString_FromString("."));
    Py_DECREF(syspath);
    Py_DECREF(sysmodule);
}

intcallModuleFunc(int array[], size_t size){
    PyObject *mymodule = PyImport_ImportModule("py_function");
    assert(mymodule != NULL);
    PyObject *myfunc = PyObject_GetAttrString(mymodule, "printlist");
    assert(myfunc != NULL);
    PyObject *mylist = PyList_New(size);
    for (size_t i = 0; i != size; ++i) {
        PyList_SET_ITEM(mylist, i, PyInt_FromLong(array[i]));
    }
    PyObject *arglist = Py_BuildValue("(O)", mylist);
    assert(arglist != NULL);
    PyObject *result = PyObject_CallObject(myfunc, arglist);
    assert(result != NULL);
    int retval = (int)PyInt_AsLong(result);
    Py_DECREF(result);
    Py_DECREF(arglist);
    Py_DECREF(mylist);
    Py_DECREF(myfunc);
    Py_DECREF(mymodule);
    return retval;
}

intmain(int argc, char *argv[]){
    initPython();

    int a[] = {1,2,3,4,5,6,7};
    callModuleFunc(a, 4);
    callModuleFunc(a+2, 5);

    Py_Finalize();
    return0;
}

py_function.py

'''py_function.py - Python source designed to ''''''demonstrate the use of python embedding'''defprintlist(mylist):
    print mylist
    return0

Post a Comment for "Embedding Python In C - Segfault"