PyArg_ParseTuple 导致分段错误
我正在尝试从我的扩展中调用 ac 函数,并将问题范围缩小到这个测试用例。
#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)。
I'm trying to call a c function from my extension and have narrowed the problem down to this test case.
#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}
};
Any ideas what I might be doing wrong. (Python version 2.6.4).
嗯。我认为你的方法的签名应该是这样的:
如果你将
test_method
作为绑定方法(即某个对象实例的方法)调用,则self
将是该对象本身。如果test_method
是模块函数,则self
是初始化模块时传递给Py_InitModule4()
的指针(如果使用self
,则为 NULL >Py_InitModule())。问题是,Python 在代码级别上不区分绑定实例方法和普通函数,这就是为什么即使您正在实现一个普通函数,也必须传递 self 。有关更多详细信息,请参阅此页面。
Hmmm. I think the signature of your method should be this:
If you are invoking your
test_method
as a bound method (i.e. a method of some object instance),self
will be the object itself. Iftest_method
is a module function,self
is the pointer passed toPy_InitModule4()
when you initialized the module (or NULL if you usedPy_InitModule()
). The thing is that Python makes no distinctions between bound instance methods and ordinary functions at the code level, that's why you have to passself
even if you are implementing a plain function.See this page for more details.