python3中的分段错误(C)

时间:2016-11-27 10:17:33

标签: python c python-3.x python-c-api

我在处理代码时收到消息Program received signal SIGSEGV, Segmentation fault。我的程序用定义的struct调用C模块。

struct

的定义
typedef struct {
    char* str;
    int order;
    int list[10][10];
} Graph;

模块的定义

static PyMethodDef GraphMethods[] = {
{ "fromString",(PyCFunction)Graph__fromString,METH_VARARGS,"desc" },
{ "order",(PyCFunction)Graph_order,METH_NOARGS,"desc" },
{ NULL }
} ;


static PyTypeObject GraphType = {
PyVarObject_HEAD_INIT( NULL,0 ) // inicjalizacja
"GL.Graph", // nazwa
sizeof( Graph ), // rozmiar
0, //
(destructor)Graph__del__, // destruktor
0,0,0,0,0,0,0,0,0,0, //
(reprfunc)Graph__str__, // obiekt -> napis
0,0,0, //
Py_TPFLAGS_DEFAULT, //
"desc.", // opis
0,0,0,0,0,0, //
GraphMethods, // metody
0,0,0,0,0,0,0, //
(initproc)Graph__init__, // inicjalizator
0, //
(newfunc)Graph__new__ // konstruktor
} ;

简单地说,我的对象由函数fromString初始化 - 当我使用这样的构造函数时:

import GL

g = GL.Graph("A?")
g.order()

(初始化函数)

static int Graph__init__(Graph *self, PyObject *args ) {
    Graph__fromString(self, args);
    printf("ORDER: %d\n", self->order);
    return 0;
}

程序在g.order()上抛出错误。

static  PyObject * Graph_order( Graph *self ) {
    int result = self->order;
    return  Py_BuildValue("i", result);
}


PyObject * Graph__fromString(Graph * self, PyObject *args) {
    char * text;
    // Check if user passed the argument
    if (PyArg_ParseTuple(args, "s", &text)) {
        self->str = text;
        int i, k;
        int n = strlen(text);

        /* magic goes here, but im sure this is working */
}
Py_RETURN_NONE;
}

我做错了什么?这个代码在普通的C中工作,当我把它移到Python时,它会在构造函数之后调用的每个方法上崩溃......

1 个答案:

答案 0 :(得分:1)

您的结构缺少PyObject_HEAD宏:

typedef struct {
    PyObject_HEAD
    char* str;
    int order;
    int list[10][10];
} Graph;

在扩展之后,这最终(除其他外)还有一个指向该类型的指针,事实上你错过了这可能会导致整个事情爆发。