是否可以在导入后修改 ctypes.Structure
的 _fields_
定义?
类似于:
from ctypes import *
class A_STRUCT(Structure):
_fields_ = [("one",c_int)]
A_STRUCT._fields_.append(("two",c_int))
x = A_STRUCT()
print x.one
print x.two
毫不奇怪,这失败了:
0
Traceback (most recent call last):
File "structEnumTest.py", line 10, in <module>
print x.two
AttributeError: 'A_STRUCT' object has no attribute 'two'
编辑
我的用例是我有两个版本的 A_STRUCT
。版本 2 与版本 1 末尾附加的附加字段相同。我希望避免发生这样的事情。在运行时之前,我不知道需要哪个版本的结构。
class A_STRUCT_V1(Structure):
_fields_ = [("one",c_int)]
class A_STRUCT_V2(Structure):
_fields_ = [("one",c_int),("two",c_int)]
最佳答案
不,正如您在 the sources 中看到的那样,PyCStructType_Type
是一个自定义元类(请参阅我刚刚指出的 C 代码中的第 327ff 行)并且 Structure
(第 4136ff 行)使用它(如 5532ff 中公开的那样)。 class
语句(特别是当来自自定义元类的 __new__
被调用以创建继承自 Structure
的新类时)是所有 C-可访问字段实际上已定义(ctypes
使其他“走私”字段无法从 Python 访问以及避免事故,这很好;-)。
您究竟想解决什么问题,但在您了解额外字段时无法通过从头开始重建 A_STRUCT
来解决?例如,如果您的问题是“旧的”A_STRUCT
的实例已经存在,那么很明显,这些实例没有您刚刚了解的新字段,因此修改类,即使通过一些令人难以置信的扭曲是可行的,也不会那么有用;-)。
关于python - ctypes.Structure 在运行时修改_fields_,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3451834/