将Python嵌入C

时间:2016-08-20 01:56:15

标签: python python-c-api

从另一个post的答案运行代码,我尝试在Linux上运行相同的代码,但是我总是遇到分段错误。在尝试通过gdb进行调试时,它表明即使在附加了所描述的当前目录的路径之后,变量mymodule仍然为NULL。谁能帮助我让我知道我错过了什么?

代码如下:

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

0 个答案:

没有答案