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

将二进制数据从Python传递到C API扩展,python,c,api,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

我正在编写一个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中的
y
y#
y*
PyArg\u ParseTuple()格式字符,但我仅限于2.6。

好的,我在

我使用了一个
PyByteArrayObject
(文档)如下:

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
现在保存字节字符串,完全符合需要。

您可以使用
“s”
,长度为
Py\u ssize\t
。@eryksun:是的,您说得对!我一定错过了。您的解决方案也会起作用,谢谢!