我创建了一个小的C包装函数,该函数需要两个字节变量:
static PyObject * wrapperfunction(PyObject * self, PyObject * args) {
const unsigned char * data;
Py_ssize_t datalen;
const unsigned char * otherdata;
Py_ssize_t otherlen;
if (!PyArg_ParseTuple(args, "y#y#", &data, &datalen, &otherdata, &otherlen))
return NULL;
some_function(data, datalen, otherdata, otherlen);
}
但是我注意到在64位Linux上,该功能在某些情况下会失败(我无法真正将它们缩小到特殊情况),并且some_function
内的段错误(Segfault)是因为data
是一个不可读的地址。
通常该地址为0x7fff00000001
我不知道为什么会这样,但是更改了代码以改为使用Py_buffer
-效果很好:
static PyObject * wrapperfunction(PyObject * self, PyObject * args) {
Py_buffer data;
Py_buffer otherdata;
if (!PyArg_ParseTuple(args, "y*y*", &data, &otherdata))
return NULL;
some_function((unsigned char *)data.buf, data.len, (unsigned char *)otherdata, otherdata.len);
}
据我所知,python文档只说y*
是首选方法,但不是y#
只能工作一次。
使用y#
的方法失败有什么原因吗?
我在debian Stretch amd64上使用Python 3.5.3。 在Windows计算机(python 3.6.4 / x64)上,相同的代码永远不会产生段错误。