如何获取 Ctypes 对象的_fields_的所有内容作为 ctypes 数组?
How to get all content of _fields_ of a Ctypes object as ctypes array?
我定义了一个示例位域如下。
如何获取 _fields_ 的值作为 list/ctypes 数组?
class packet_fields(Structure):
_fields_ = [
('length_present', c_int, 1),
('attribute_present', c_int, 1)
]
看看这段代码。
使用此代码结构,您可以访问数组或数组中的元素。
class packet_fields():
liste = [
('length_present', "dgr1", 1),
('attribute_present', "dgr2", 1)
]
dz= packet_fields()
print(dz.liste[1])
不确定你的问题,所以这里有一个关于如何获取值的例子:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import ctypes
class packet_fields(ctypes.Structure):
_fields_ = [
('length_present', ctypes.c_int, 1),
('attribute_present', ctypes.c_int, 1)
]
if __name__ == '__main__':
pf = packet_fields()
pf.length_present = 0
pf.attribute_present = 1
# list fields: name and type
for field in pf._fields_:
print(f"Name: {field[0]}; type: {field[1]}")
# access value
print(f"length_present: {pf.length_present}")
print(f"attribute_present: {pf.attribute_present}")
# all fields as a list
fields_list = [getattr(pf, f[0]) for f in pf._fields_]
print(f"As list: {fields_list}")
输出:
Name: length_present; type: <class 'ctypes.c_long'>
Name: attribute_present; type: <class 'ctypes.c_long'>
length_present: 0
attribute_present: -1
As list: [0, -1]
如果您担心 -1
(而不仅仅是 1
),请将 c_int
替换为 c_uint
。
我定义了一个示例位域如下。
如何获取 _fields_ 的值作为 list/ctypes 数组?
class packet_fields(Structure):
_fields_ = [
('length_present', c_int, 1),
('attribute_present', c_int, 1)
]
看看这段代码。 使用此代码结构,您可以访问数组或数组中的元素。
class packet_fields():
liste = [
('length_present', "dgr1", 1),
('attribute_present', "dgr2", 1)
]
dz= packet_fields()
print(dz.liste[1])
不确定你的问题,所以这里有一个关于如何获取值的例子:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import ctypes
class packet_fields(ctypes.Structure):
_fields_ = [
('length_present', ctypes.c_int, 1),
('attribute_present', ctypes.c_int, 1)
]
if __name__ == '__main__':
pf = packet_fields()
pf.length_present = 0
pf.attribute_present = 1
# list fields: name and type
for field in pf._fields_:
print(f"Name: {field[0]}; type: {field[1]}")
# access value
print(f"length_present: {pf.length_present}")
print(f"attribute_present: {pf.attribute_present}")
# all fields as a list
fields_list = [getattr(pf, f[0]) for f in pf._fields_]
print(f"As list: {fields_list}")
输出:
Name: length_present; type: <class 'ctypes.c_long'>
Name: attribute_present; type: <class 'ctypes.c_long'>
length_present: 0
attribute_present: -1
As list: [0, -1]
如果您担心 -1
(而不仅仅是 1
),请将 c_int
替换为 c_uint
。