如何在 Python 3 个字符串上使用 memoryview?

How to use memoryview on Python 3 strings?

在Python3、执行:

memoryview("this is a string")

产生错误:

TypeError: memoryview: str object does not have the buffer interface

我应该怎么做才能使 memoryview 接受字符串,或者我应该对我的字符串进行什么转换才能被 memoryview 接受?

docs 开始,memoryview 仅适用于支持 bytesbytearray 接口的对象。 (这些是相似的类型,只是前者是只读的。)

Python3 中的字符串不是我们可以直接操作的原始字节缓冲区,而是 immutable sequences of Unicode runes or characters. A str can be converted to a buffer, though, by encoding it with any of the supported string encodings,如 'utf-8'、'ascii' 等

memoryview(bytes("This is a string", encoding='utf-8'))

请注意,bytes() 调用必然涉及将字符串数据转换并复制到 memoryview 可访问的新缓冲区中。从前一段可以明显看出,不可能直接在 str 的数据上创建 memoryview

考虑到错误已经清楚地说明了问题 ,我只会补充一点,您可以从字符串中简洁地创建一个 memoryview 实例,如下所示:

memoryview( b"this is a string" )