python - 将二进制数据从 python 2.7 获取到 C 模块的正确方法是什么

标签 python python-2.7 python-c-extension

我正在从 python 文件中读取二进制数据,并尝试将该数据发送到 c 模块。在Python中,数据的读取方式如下

file = open("data", "rb")
data = file.read()

如果可能的话,我希望数据作为指向缓冲区的指针和 c 中的长度。我正在使用 PyArg_ParseTuple 来获取 c 模块中的参数。我注意到在 python 3+ 中,有一个用于二进制数据的 y/y*/y# 格式说明符,但我需要在 python 2.7 中使用等效的方法。

谢谢

最佳答案

您应该调查Buffer Api .

来自文档:

These functions can be used by an object to expose its data in a raw, byte-oriented format. Clients of the object can use the buffer interface to access the object data directly, without needing to copy it first.

Two examples of objects that support the buffer interface are strings and arrays. The string object exposes the character contents in the buffer interface’s byte-oriented form. An array can also expose its contents, but it should be noted that array elements may be multi-byte values.

例如(在 C++ 中):

void* ExtractBuffer(PyObject* bufferInterfaceObject, Py_buffer& bufferStruct)
{
    if (PyObject_GetBuffer(bufferInterfaceObject, &bufferStruct, PyBUF_SIMPLE) == -1)
        return 0;

    return (void*)bufferStruct.buf;
}

当您不再需要 bufferStruct 时,不要忘记释放它:

PyBuffer_Release(&bufferStruct);

关于python - 将二进制数据从 python 2.7 获取到 C 模块的正确方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14717200/

相关文章:

带有 Pandas : How does one recover the non intersecting parts of two dataframes? 的 Python 2.7

python - 在 python 中总结列表——有更好的方法吗?

python - 如何在 Python 图中以弧度为单位设置 y 轴?

python-2.7 - 错误:- tensorboard: command not found .但是,在输入locatetensorboard时,我得到了位置

python - 将 3 维 numpy 数组传递给 C

python - 使用 Python 和 Flask 长时间运行的任务

python - 如何在保持元组顺序的同时,根据元组的索引值从列表中删除重复的元组?

python - txt 文件中的参数

python - 如果 PyModule_Add* 函数失败,C 扩展是否应该在模块初始化中失败?

Python 3 兼容性问题