单线程C程序中Py_Finalize(python 2.5)的段错误

问题描述 投票:2回答:2

在下面的Hello World C程序中,我正在扩展和嵌入Python。

spam.c

#include <Python.h>

static PyObject *
spam_echo(PyObject *self, PyObject *args) {
    const char *command;
    int sts;

    if (!PyArg_ParseTuple(args, "s", &command))
        return NULL;
    sts = printf("%s\n", command);
    return Py_BuildValue("i", sts);
}

static PyMethodDef SpamMethods[] = {
    {"echo", spam_echo, METH_VARARGS, "Prints passed argument"},
    {NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC
initspam(void) {
    (void) Py_InitModule("spam", SpamMethods);
}

int main(int argc, char *argv[]) {
    PyObject *args;
    PyObject *arg;
    PyObject *result;
    PyObject *moduleName;
    PyObject *module;
    PyObject *func;

    Py_SetProgramName(argv[0]);
    Py_Initialize();
    initspam();

    PyRun_SimpleFile(fopen("foo.py", "r"), "foo.py");

    moduleName = PyString_FromString("__main__");
    module = PyImport_Import(moduleName);
    Py_DECREF(moduleName);
    if (!module) {
        return 1;
    }

    func = PyObject_GetAttrString(module, "foo");
    Py_DECREF(module);
    if (!func || !PyCallable_Check(func)) {
        return 1;
    }

    args = PyTuple_New(1);
    arg = Py_BuildValue("s", "hello world");
    PyTuple_SetItem(args, 0, arg);

    result = PyObject_CallObject(func, args);
    Py_DECREF(arg);
    Py_DECREF(args);
    Py_DECREF(func);

    printf("== before\n");
    Py_Finalize();
    printf("== after\n");
}

这是调用的Python程序:

foo.py

#!/usr/bin/python

import spam

def foo(cmd):
    spam.echo(cmd)

我编译时

gcc spam.c -I/usr/include/python2.5/ -lpython2.5

使用GCC 4.2.4-1ubuntu4,我在Ubuntu Hardy上使用python2.5-dev软件包。

基本上,我在Py_Finalize上有一个段错误,如输出所示:

hello world
== before
Segmentation fault
python c segmentation-fault cpython
2个回答
3
投票

交换行Py_DECREF(args);Py_DECREF(arg);解决了这个问题。该段错误是在已释放arg后访问Py_DECREF(args)的结果。


0
投票

也许交换行已在Python2中修复了它,但它本来应该没有,对于Python 3也肯定不会。请再次查看代码段:

© www.soinside.com 2019 - 2024. All rights reserved.