ctypes 结构体和共用体 Structures and unions

结构体必然是继承 Structure基类

共用体必然是继承 Union基类

这两个类都是ctypes定义的,每一个子类必须定义 _fields_ 属性

这个属性的格式必然是一个集合,集合的元素是一个二元组, [(name,type),(name,type),(name,type)]

type必然是一个 c_type类型,或者是一个类似的还有衍生类:structure,union,array,pointer

>>> from ctypes import *
>>> class POINT(Structure):
...     _fields_ = [("x", c_int),
...                 ("y", c_int)]
...
>>> point = POINT(10, 20)
>>> print(point.x, point.y)
10 20
>>> point = POINT(y=5)
>>> print(point.x, point.y)
0 5
>>> POINT(1, 2, 3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many initializers
>>>

 和c一样,结构体可以包含结构体,也可以包含自身的指针,不能包含自身,否则会无限迭代。如下。

>>> class RECT(Structure):
...     _fields_ = [("upperleft", POINT),
...                 ("lowerright", POINT)]
...
>>> rc = RECT(point)
>>> print(rc.upperleft.x, rc.upperleft.y)
0 5
>>> print(rc.lowerright.x, rc.lowerright.y)
0 0
>>>

内置嵌套的结构体初始化

>>> class RECT(Structure):
...     _fields_ = [("upperleft", POINT),
...                 ("lowerright", POINT)]
...
>>> rc = RECT(point)
>>> print(rc.upperleft.x, rc.upperleft.y)
0 5
>>> print(rc.lowerright.x, rc.lowerright.y)
0 0
>>>

文件描述符有助于查看类的数据,特别是在debug的时候会很方便。

>>> print(POINT.x)
<Field type=c_long, ofs=0, size=4>
>>> print(POINT.y)
<Field type=c_long, ofs=4, size=4>
>>>

猜你喜欢

转载自blog.csdn.net/rubikchen/article/details/89436984