gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 05:49:52 30 4
gpt4 key购买 nike

我正在从 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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com