python - 如何在Python中将多个整数转换为c_ubyte的ctypes数组

标签 python types casting initialization ctypes

如何将一串以冒号分隔的十六进制数字转换为 c_ubyte 的 ctypes 数组?根据ctypes docs ,我可以转换一个硬编码的集合,如下所示:

>>> from ctypes import *
>>> x = (c_ubyte * 6) (1, 2, 3, 4, 5, 6)
>>> x
<__main__.c_ubyte_Array_6 object at 0x480c5348>

或者,像这样:

>>> XObj = c_ubyte * 6
>>> x = XObj(1, 2, 3, 4, 5, 6)
>>> x
<__main__.c_ubyte_Array_6 object at 0x480c53a0>

但是,我无法弄清楚如何转换变量列表,例如通过拆分字符串生成的变量列表:

>>> mac = 'aa:bb:cc:dd:ee:ff'
>>> j = tuple(int(z,16) for z in mac.split(':'))
>>> j
(170, 187, 204, 221, 238, 255)
>>> x = (c_ubyte * 6) (j)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: an integer is required
>>> XObj = c_ubyte * 6
>>> x = XObj(j)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: an integer is required

我错过了什么?

谢谢!

最佳答案

问题是,在您提供的第一个示例中,您通过为 XObj 调用提供 6 个参数来正确使用 ctypes,而在第二个示例(使用 mac 地址)中,您尝试调用相同的对象 c_ubyte * 6,给它一个元组,但不是 6 个值,因此使用 *args 表示法进行转换:

from c_types import c_ubyte

mac = 'aa:bb:cc:dd:ee:ff'
j = tuple(int(z,16) for z in mac.split(':'))

converted = (c_ubyte * 6)(*j)  # *j here is the most signigicant part
print converted

结果是:

<__main__.c_ubyte_Array_6 object at 0x018BD300>

正如预期的那样。

关于python - 如何在Python中将多个整数转换为c_ubyte的ctypes数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12013599/

相关文章:

没有参数但在 Julia 中有类型的函数

python - 为什么 enumerate、zip、range 类型不属于 types.GeneratorType?

scala - 转换不兼容的 DecimalType 与 ClassCastException 时的 Apache Spark Null 值

c# - InvalidCastException : Unable to cast object of type 'System.TimeSpan' to type 'System.Nullable` 1[System. 日期时间]'

Python:typing.cast 与内置类型转换

python - Pytorch 中 [-1,0] 的维度范围是多少?

Python枚举列表设置开始索引但不增加结束计数

python - 从字典中查找句子字谜的有效方法?

C++:char** 到 const char** 的转换

python - 尝试创建没有重叠的 Sprite