将二进制数据从Python传递到C API扩展

时间:2012-12-18 15:21:39

标签: python c api

我正在编写一个Python( 2.6 )扩展,我有一种情况需要将不透明的二进制blob(带有嵌入的空字节)传递给我的扩展。

以下是我的代码片段:

from authbind import authenticate

creds = 'foo\x00bar\x00'
authenticate(creds)

引发以下内容:

TypeError: argument 1 must be string without null bytes, not str

以下是一些authbind.cc:

static PyObject* authenticate(PyObject *self, PyObject *args) {

    const char* creds;

    if (!PyArg_ParseTuple(args, "s", &creds))
        return NULL;
}

到目前为止,我已经尝试将blob作为原始字符串传递,例如creds = '%r' % creds,但这不仅为我提供了字符串周围的嵌入式引号,还将\x00字节转换为字符串表示形式,我不想在C中乱七八糟。

我怎样才能完成我的需要?我知道3.2中的yy#y* PyArg_ParseTuple()格式字符,但我限制在2.6。

1 个答案:

答案 0 :(得分:4)

好的,我在this link的帮助下找到了答案。

我使用了PyByteArrayObject(文档here),如下所示:

from authbind import authenticate

creds = 'foo\x00bar\x00'
authenticate(bytearray(creds))

然后在扩展代码中:

static PyObject* authenticate(PyObject *self, PyObject *args) {

    PyByteArrayObject *creds;

    if (!PyArg_ParseTuple(args, "O", &creds))
        return NULL;

    char* credsCopy;
    credsCopy = PyByteArray_AsString((PyObject*) creds);
}

credsCopy现在保存字节串,完全符合它们的要求。