ctypes API 似乎不支持此功能。当。。。的时候Field
repr <Field type=c_long ..>
创建后,会从嵌入类型中检索名称,如下所示:
name = ((PyTypeObject *)self->proto)->tp_name;
对于您所在领域的会员self->proto
指着c_long
,但我在 Python 2.7 中找不到位置cfield.c您可以在其中检索值self->proto
本身。您可能被迫:
- 创建您自己的映射
name
-> type
.
- (恶心)解析代表
<Field type=X
并使用getattr(ctypes, X)
获取类型对象。
只是为了跟进一个例子选项1),这是一个类装饰器,它为您创建类型映射,添加_typeof(cls, fld)
类方法:
from ctypes import *
def typemap(cls):
_types = dict((getattr(cls, t), v) for t, v in cls._fields_)
setattr(cls, '_typeof', classmethod(lambda c, f: _types.get(f)))
return cls
@typemap
class A(Structure):
_fields_ = [("one", c_long),
("two", c_char),
("three", c_byte)]
print A._typeof(A.one), A._typeof(A.two), A._typeof(A.three)
Result:
<class 'ctypes.c_long'> <class 'ctypes.c_char'> <class 'ctypes.c_byte'>