2

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

我错过了什么?

谢谢!

4

1 回答 1

4

问题是,在您提供的第一个示例中,您通过为 XObj 调用提供 6 个参数来正确使用 ctypes,而在第二个示例(使用 mac 地址)中,您尝试调用相同的 object 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>

正如预期的那样。

于 2012-08-17T21:58:52.973 回答