Running the code from the answer of another post, I tried running the same on Linux, however I always encounter a segmentation fault. On trying to debug through gdb, it shows that the variable mymodule remains NULL even after appending the path of the current directory as described. Can anyone help me in letting me know what am I missing?
The code is as follows:
pyarray.c
#include <Python.h>
void initPython(void)
{
Py_Initialize();
PyObject *sysmodule = PyImport_ImportModule("sys");
PyObject *syspath = PyObject_GetAttrString(sysmodule, "path");
PyList_Append(syspath, PyBytes_FromString("."));
Py_DECREF(syspath);
Py_DECREF(sysmodule);
}
int callModuleFunc(int array[], size_t size) {
PyObject *pname=PyBytes_FromString((char *)"py_function");
PyObject *mymodule = PyImport_Import(pname);
if (mymodule==NULL)
{
printf("Abort");
exit(-1);
}
assert(mymodule != NULL);
PyObject *myfunc = PyObject_GetAttrString(mymodule,"printlist");
assert(myfunc != NULL);
PyObject *mylist = PyList_New(size);
size_t i;
for (i = 0; i != size; ++i) {
PyList_SET_ITEM(mylist, i, PyLong_FromLong(array[i]));
}
PyObject *arglist = Py_BuildValue("(O)", mylist);
assert(arglist != NULL);
PyObject *result = PyObject_CallObject(myfunc, arglist);
assert(result != NULL);
int retval = (int)PyLong_AsLong(result);
Py_DECREF(result);
Py_DECREF(arglist);
Py_DECREF(mylist);
Py_DECREF(myfunc);
Py_DECREF(mymodule);
return retval;
}
int main(int argc, char *argv[])
{
initPython();
int a[] = {1,2,3,4,5,6,7};
callModuleFunc(a, 4);
callModuleFunc(a+2, 5);
Py_Finalize();
return 0;
}
py_function.py
def printlist(mylist):
print mylist
return 0