为什么无法从数组对象获取Py_buffer? [英] Why is it not possible to get a Py_buffer from an array object?

查看:111
本文介绍了为什么无法从数组对象获取Py_buffer?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于数组的Python文档明确指出数组符合缓冲区接口。它甚至建议不要使用buffer_info()方法。但是,当我尝试使用PyObject_GetBuffer()从C / C ++代码获取Py_Buffer或使用python的memoryview时,就会失败。

The python documentation on array clearly states that the array conforms to the buffer interface. It even suggest not using the buffer_info() method. But when I try to get a Py_Buffer from C/C++ code with PyObject_GetBuffer() or use python's memoryview, I get a failure.

例如,在python中(我使用版本2.7):

For example, in python (I use version 2.7):

>>> a = array.array('c')
>>> memoryview(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot make memory view because object does not have the buffer interface

实际上,无法进行内存视图当我搜索python的代码库时,只有bytearrayobject(bytearray),memoryobject(memoryview)和stringobject(str)上设置了必需的Py_TPFLAGS_HAVE_NEWBUFFER标志。据我了解,该文档是错误的。 数组不支持缓冲区接口。

In fact, when I search python's code base, only bytearrayobject (bytearray), memoryobject (memoryview), and stringobject (str) have the required Py_TPFLAGS_HAVE_NEWBUFFER flag set on them. To my understanding, the documentation is wrong; array does not support the buffer interface.

我可以使用支持缓冲区接口的字节数组,问题是我需要数组的实用fromfile ()读取我可以在C / C ++代码中使用的缓冲区的方法。

I could use bytearray which supports the buffer interface, the problem is that I need the array's practical fromfile() method to read in a buffer that I can use in my C/C++ code.

有没有一种替代方法可以让我将文件读入缓冲区并使用C代码中的此缓冲区,并且不涉及内存副本? (我想处理较大的二进制文件,而复制是不太理想的选择。)

Is there an alternative that would allow me to read a file into a buffer and use this buffer from C code, and not involve memory copies ? (I want to treat big binary files and copying is a less desirable option).

推荐答案

memoryview 仅适用于支持Python 3缓冲区接口的对象。 Python 3中的 array.array 可以,但Python 2.7中没有。您可能要为此提交错误报告。只需使用 bytearray (或 str (如果您以只读方式使用))。两者都支持 memoryview 很好。

memoryview works only on objects that support the Python 3 buffer interface. array.array in Python 3 does, but it doesn't in Python 2.7. You might want to file a bug report for that. Simply use use bytearray (or str if you're using it read-only). Both support memoryview just fine.

这篇关于为什么无法从数组对象获取Py_buffer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆