如何将一串以冒号分隔的十六进制数字转换为 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/