python - python3中的段错误(C)

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

当我使用代码时,我收到消息程序收到信号 SIGSEGV,段错误。我的程序使用定义的结构调用 C 模块。

结构体的定义

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 时,它在构造函数之后调用的每个方法上都会崩溃......

最佳答案

您的结构缺少 PyObject_HEAD 宏:

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

扩展后,它最终(除其他外)还包含一个指向该类型的指针,事实上,您错过了它可能会导致整个事情崩溃。

关于python - python3中的段错误(C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40827821/

相关文章:

string - python : remove single quotation in a string in a list

python - python中大数的浮点除法

python - 快速有效地计算已知特征值的特征向量

python - 在 Amazon EC2 集群上使用 python scikit-learn 库执行网格搜索

c - "context"这个词在结构中通常是什么意思?

c - 从图表开始

python - 如何在 Python 3 pyspark 中反转 RDD 中的键和值?

python ,OpenCV : unable to make custom LBP cascade using opencv_traincascade

python 使用 cookie 请求登录

java - 错误 : parse error before "double" (cygwin)