Python PyArg_语法元组导致分段错误
我试图从扩展中调用一个c函数,并将问题缩小到这个测试用例Python PyArg_语法元组导致分段错误,python,c,argument-passing,python-c-extension,Python,C,Argument Passing,Python C Extension,我试图从扩展中调用一个c函数,并将问题缩小到这个测试用例 #import "Python.h" ... // Called from python with test_method(0, 0, 'TEST') static PyObject* test_method(PyObject *args) { int ok, x, y, size; const char *s; // this causes Segmentation fault //ok = PyA
#import "Python.h"
...
// Called from python with test_method(0, 0, 'TEST')
static PyObject*
test_method(PyObject *args)
{
int ok, x, y, size;
const char *s;
// this causes Segmentation fault
//ok = PyArg_ParseTuple(args, "iis#", &x, &y, &s, &size);
// also segfaults
//if(ok) PyErr_SetString(PyExc_SystemError, 'Exception');
// this does not cause segfault but fills the variables with garbage
ok = PyArg_ParseTuple(&args, "iis#", &x, &y, &s, &size);
// Example: >test_method 0, 37567920, (garbage)
printf(">test_method %d, %d, %s\n", x, y, s);
/* Success */
Py_RETURN_NONE;
}
static PyMethodDef testMethods[] =
{
{"test_method", test_method, METH_VARARGS,
"test_method"},
...
{NULL, NULL, 0, NULL}
};
知道我做错了什么吗。(Python版本2.6.4)。Hmmm。我认为您的方法的签名应该是:
static PyObject* test_method(PyObject* self, PyObject* args)
如果将test\u方法
作为绑定方法(即某个对象实例的方法)调用,self
将是对象本身。如果test\u方法
是一个模块函数,self
是初始化模块时传递给Py\u InitModule4()
的指针(如果使用Py\u InitModule()
,则为NULL)。问题是Python在代码级别对绑定实例方法和普通函数没有区别,这就是为什么即使实现普通函数,也必须传递self
更多详情请参见。就是这样,出于好奇,*self指的是什么?模块?我扩展了我的回答来回答这个问题。