从字符串解包工作:
>>> 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 "", line 1, in
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,)
但我明确地试图避免复制可能的大量内存.
解决方法:
看起来像buffer()是解决方案:
>>> struct.unpack_from('>h', buffer(bytearray('zabx')), 1)
(24930,)