← 中文资源

简体中文版本

用 BytesIO.getbuffer 暴露零拷贝可写内存视图

通过 io.BytesIO.getbuffer() 获取指向内部缓冲的零拷贝可写 memoryview 原地修改字节,并演示释放视图前扩容触发 BufferError 的保护契约。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

locked while view open: Existing exports of data: object cannot be re-sized
final bytes: PKT-0042-READY-OK

实现说明

顶层就这几处状态:stream。

使用要点

  • 只跑在标准库上;没有要装的东西。
  • 跑完文件,输出里会留下标记——locked while view open:、final bytes:。

常见问题

运行时需要 npm、pip、cargo 之类帮忙吗?

不需要——包管理器在这里无事可做,没有任何声明。 全部导入都来自标准库:io。 文件用顶层绑定保存自己的状态:stream。

核心语句

with stream.getbuffer() as view:
    view[4:8] = b"0042"
    try:
        # Resizing writes fail with BufferError while an exported view is still alive
        stream.write(b"-TAIL")
    except BufferError as exc:
        print("locked while view open:", exc)

代码示例

import io

stream = io.BytesIO(b"PKT-0000-READY")

# getbuffer() exports a writable memoryview directly over the internal buffer
with stream.getbuffer() as view:
    view[4:8] = b"0042"
    try:
        # Resizing writes fail with BufferError while an exported view is still alive
        stream.write(b"-TAIL")
    except BufferError as exc:
        print("locked while view open:", exc)

# Once the memoryview context exits, resizing writes work again
stream.seek(0, io.SEEK_END)
stream.write(b"-OK")
print("final bytes:", stream.getvalue().decode("ascii"))