从阅读另一个post开始,我试图将一些Python代码编译成C:
main.c
#include <Python.h>
int callModuleFunc(int array[], size_t size) {
PyObject *mymodule = PyImport_ImportModule("py_function");
PyObject *myfunc = PyObject_GetAttrString(mymodule, "printlist");
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);
PyObject *result = PyObject_CallObject(myfunc, arglist);
int retval = (int)PyInt_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[])
{
int a[] = {1,2,3,4};
callModuleFunc(a, 4);
return 0;
}
py公司_函数.py
^{pr2}$然后我用:
gcc main.c -I/usr/include/python2.7 -lpython2.7
但后来我运行了这个应用程序,它给了我一个分段错误:
/a.out
[1] 18890 segmentation fault ./a.out
我有什么遗漏吗?在
您的代码有几个问题:
PyImport_ImportModule()
找不到python文件,因为在嵌入式python中,启动时没有一个初始模块,搜索可以相对于该模块工作。修复方法是显式地将当前目录包含在sys.path
中。在"(O)"
中的{'O'
。在printlist
函数应该返回一个值(因为这是C代码所期望的)。在这应该是有效的:
main.c
py公司_函数.py
^{pr2}$相关问题 更多 >
编程相关推荐