python - 将二进制数据从 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 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。

最佳答案

好的,我在 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 现在完全按照需要保存字节串。

关于python - 将二进制数据从 Python 传递到 C API 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13936068/

相关文章:

c - 我需要用 C 解析一些月份名称

api - Golang HTTP 请求返回 200 响应但正文为空

node.js - 如何在express 4.0中使用request.query时转义特殊字符

rest - 如何保护 flask 上的 REST Api

python - Groupby 并在 Python 的两列中查找相似或相同的项目

python - 训练神经网络的问题

python - IF-ELIF 语句嵌套

c++ - 将下载的种子保存在内存中而不是文件 libtorrent

c++ - 模幂(模算术中的幂)

c# - C++ 中的变量变量名