0

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
Community
  • 1
  • 1
suzaku
  • 11
  • 4
  • 1
    You have not specified the python version you want to use. That code seemed to work with python 2.7. – J.J. Hakala Aug 20 '16 at 03:32
  • 1
    is `py_function` actually a `.c` file? If so importing it won't work and you probably want to rename it as a `.py` file? – DavidW Aug 20 '16 at 09:30
  • Pardon for the typo, the py_function is actually a python file. I am using Python 3.4.3 for this purpose on the Linux environment. However, the main issue arising is it being unable to import the module (thus prints "Abort" and exits ) – suzaku Aug 22 '16 at 08:20
  • I got it working now, the python file had a syntax error as it was built in python 2, and was being used in Python 3. Thanks for the help. – suzaku Aug 22 '16 at 09:11

0 Answers0