gpt4 book ai didi

python - python3中的段错误(C)

转载 作者:行者123 更新时间:2023-11-30 15:03:09 25 4
gpt4 key购买 nike

当我使用代码时,我收到消息程序收到信号 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com