在C Segfau中嵌入Python

2024-09-29 21:40:29 发布

您现在位置:Python中文网/ 问答频道 /正文

从阅读另一个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

我有什么遗漏吗?在


Tags: pysizeincludemainresultmyfuncarrayint
1条回答
网友
1楼 · 发布于 2024-09-29 21:40:29

您的代码有几个问题:

  1. ^未调用{}。在
  2. PyImport_ImportModule()找不到python文件,因为在嵌入式python中,启动时没有一个初始模块,搜索可以相对于该模块工作。修复方法是显式地将当前目录包含在sys.path中。在
  3. "(O)"中的{}应该使用大写'O'。在
  4. printlist函数应该返回一个值(因为这是C代码所期望的)。在

这应该是有效的:

main.c

#include <Python.h>

void initPython()
{
    Py_Initialize();
    PyObject *sysmodule = PyImport_ImportModule("sys");
    PyObject *syspath = PyObject_GetAttrString(sysmodule, "path");
    PyList_Append(syspath, PyString_FromString("."));
    Py_DECREF(syspath);
    Py_DECREF(sysmodule);
}

int callModuleFunc(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;
}

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公司_函数.py

^{pr2}$

相关问题 更多 >

    热门问题