我正在尝试将整数列表转换为 ctypes 短裤数组。然后我想将该数组分配给 BigEndianStructure 中的一个字段。我尝试这样做:
from ctypes import BigEndianStructure, c_uint16
class Test(BigEndianStructure):
_pack_ = 1
_fields_ = [('arr', c_uint16 * 10)]
num_list = [45, 56, 23]
tester = Test()
short_array = c_uint16 * 10
tester.arr = short_array.from_buffer_copy(bytes(num_list))
但它不喜欢列表比预期的小:
Traceback (most recent call last):
File "test.py", line 10, in <module>
tester.arr = short_array.from_buffer_copy(bytes(num_list))
ValueError: Buffer size too small (3 instead of at least 20 bytes)
然后我尝试扩展列表并将整数转换为大端字节:
new_list = num_list[:10] + [0]*(10-len(num_list))
buffer = b''
for item in new_list:
buffer += item.to_bytes(2, byteorder='big')
tester.arr = short_array.from_buffer_copy(buffer)
但它提示缓冲区不是“be_array”,我假设这与字节顺序有关:
Traceback (most recent call last):
File "test.py", line 14, in <module>
tester.arr = short_array.from_buffer_copy(buffer)
TypeError: incompatible types, c_ushort_Array_10 instance instead of c_ushort_be_Array_10 instance
我是不是想太多了?有人对如何解决这个问题有任何建议吗?
编辑:从注释中澄清,C中相应的结构有一个uint16_t arr[MAX_LEN],其中MAX_LEN=10。因此,如果传递的数组不是完整的 MAX_LEN,我想发送一个 0 填充的数组。
最佳答案
对 BigEndianStructure 的支持很少。您无法创建 c_ushort_be
或 c_ushort_be_Array_10
,但如果您的列表比数组短,则可以分配给字符串切片,并且它将执行正确的操作:
from ctypes import *
from binascii import hexlify
class Test(BigEndianStructure):
_fields_ = [('arr', c_uint16 * 10)]
num_list = [45, 56, 23]
tester = Test()
tester.arr[:len(num_list)] = num_list
print(hexlify(bytes(tester)))
输出(原始结构的十六进制表示):
b'002d003800170000000000000000000000000000'
另请参阅struct模块。它可能适合您的需求。
关于Python Ctypes : convert list of integers to array of shorts,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61599588/