Mat*_*att 7 python ctypes bytearray python-2.7
问题:
我试图做的:
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)
Run Code Online (Sandbox Code Playgroud)
这里的问题是struct.pack_into抱怨只读缓冲区.我已经查看了内存视图,因为它们可以创建读/写视图,但是它们不允许您像缓冲区函数那样指定偏移量和大小.
如何使用struct.unpack_from和struct.pack_into将多个零拷贝视图添加到可读,可写且可以访问/修改的字节缓冲区中
在2.6+中,ctypes数据类型有一个from_buffer采用可选偏移量的方法.它期望一个可写缓冲区,否则将引发异常.(对于readonly缓冲区来说from_buffer_copy.)这里是你的例子的快速翻译,以使用ctypeschar数组:
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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7326 次 |
| 最近记录: |