Python Ctypes : convert list of integers to array of shorts

标签 python python-3.x ctypes endianness

我正在尝试将整数列表转换为 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_bec_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/

相关文章:

python - 将日期字符串 (YYYY/YYYY_mm.mdf) 转换为可用的日期 Python

python - 为什么 python dict 键/值不像鸭子一样嘎嘎叫?

python - 这些奇特的 TypeVar 的 PyCharm 生成了什么?

python - 列表值的字典理解

python - 如何将 c_uint 的 ctypes 数组转换为 numpy 数组

python - 在 python 中从浮点元组列表构建 c 数组的最快方法是什么?

python - 存储在列表中的循环中的 Lambda,仅打印最后一个循环评估的值,而不打印与所有循环迭代不同的值

python - str_replace_all() r 在 python 中等效

python - "think python 3"书中day_num问题的解决方案

python - ctypes:如何正确更新指针?