`struct.unpack_from` 不能与 `bytearray` 一起使用?

5 投票
1 回答
6838 浏览
提问于 2025-04-17 19:26

从字符串中解包是可以的:

>>> import struct
>>> struct.unpack('>h', 'ab')
(24930,)
>>> struct.unpack_from('>h', 'zabx', 1)
(24930,)

但是如果是 bytearray 的话:

>>> struct.unpack_from('>h', bytearray('zabx'), 1)
Traceback (most recent call last):
  File "<ipython-input-4-d58338aafb82>", line 1, in <module>
    struct.unpack_from('>h', bytearray('zabx'), 1)
TypeError: unpack_from() argument 1 must be string or read-only buffer, not bytearray

这看起来有点奇怪。我到底应该怎么处理呢?显然我可以:

>>> struct.unpack_from('>h', str(bytearray('zabx')), 1)
(24930,)

但我其实是想要避免复制可能很大的内存。

1 个回答

6

看起来 buffer() 是个解决办法:

>>> struct.unpack_from('>h', buffer(bytearray('zabx')), 1)
(24930,)

buffer() 不是原始数据的副本,而是对原始数据的一个视图:

>>> b0 = bytearray('xaby')
>>> b1 = buffer(b0)
>>> b1
<read-only buffer for ...>
>>> b1[1:3]
'ab'
>>> b0[1:3] = 'nu'
>>> b1[1:3]
'nu'

另外,你(我?)也可以直接使用 Python 3;这个限制就没有了:

Python 3.2.3 (default, Jun  8 2012, 05:36:09) 
[GCC 4.7.0 20120507 (Red Hat 4.7.0-5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import struct
>>> struct.unpack_from('>h', b'xaby', 1)
(24930,)
>>> struct.unpack_from('>h', bytearray(b'xaby'), 1)
(24930,)
>>> 

撰写回答