簡體   English   中英

Python可寫緩沖區/內存視圖到數組/ bytearray / ctypes字符串緩沖區

[英]Python writable buffer/memoryview to array/bytearray/ctypes string buffer

問題:

  • 固定大小記錄的二進制數據
  • 想要使用struct.unpack_from和struct.pack_into來操作二進制數據
  • 不需要數據的副本
  • 想要多次查看內存以簡單地抵消計算等。
  • 數據可以在array.array bytearray或ctypes字符串緩沖區中

我試圖做的:

part1 = buffer(binary_data, 0, size1)
part2 = buffer(binary_data, size1, size2)
part3 = buffer(binary_data, size1 + size2) # no size is given for this one as it should consume the rest of the buffer
struct.pack_into('I', part3, 4, 42)

這里的問題是struct.pack_into抱怨只讀緩沖區。 我已經查看了內存視圖,因為它們可以創建讀/寫視圖,但是它們不允許您像緩沖區函數那樣指定偏移量和大小。

如何使用struct.unpack_from和struct.pack_into將多個零拷貝視圖添加到可讀,可寫且可以訪問/修改的字節緩沖區中

在2.6+中,ctypes數據類型具有from_buffer方法,該方法采用可選的偏移量。 它期望一個可寫緩沖區,否則會引發異常。 (對於readonly緩沖區,有from_buffer_copy 。)這里是你的例子的快速翻譯,以使用ctypes char數組:

from ctypes import *
import struct

binary_data = bytearray(24)
size1 = size2 = 4
size3 = len(binary_data) - size1 - size2

part1 = (c_char * size1).from_buffer(binary_data)
part2 = (c_char * size2).from_buffer(binary_data, size1)
part3 = (c_char * size3).from_buffer(binary_data, size1 + size2)
struct.pack_into('4I', part3, 0, 1, 2, 3, 4)

>>> binary_data[8:]
bytearray(b'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00')

>>> struct.unpack_from('4I', part3)
(1, 2, 3, 4)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM