ctypes.Structure在运行时修改_fields_

Mar*_*ark 2 python struct ctypes field runtime

是否可以修改导入后的_fields_定义ctypes.Structure

就像是:

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
Run Code Online (Sandbox Code Playgroud)

毫不奇怪,这失败了:

0
Traceback (most recent call last):
  File "structEnumTest.py", line 10, in <module>
    print x.two
AttributeError: 'A_STRUCT' object has no attribute 'two'
Run Code Online (Sandbox Code Playgroud)

EDITS

我的用例是我有两个版本的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)]
Run Code Online (Sandbox Code Playgroud)

Ale*_*lli 5

不,正如你在源代码中看到的那样,PyCStructType_Type是一个自定义元类(参见我刚刚指出的C代码中的Structure第327ff行)和(第4136ff行)使用它(在5532ff中公开).该class语句(特别是当__new__调用自定义元类来创建继承自的新类Structure时)是所有C可访问字段实际定义的时候(并且很好ctypes地使其他"走私进入"字段无法从Python中访问)避免事故;-).

确切地说,您正在尝试解决的问题是,A_STRUCT在您了解额外字段时,无法通过从头开始重建来解决这个问题?例如,如果您的问题是已经存在"旧"的实例,那么A_STRUCT很明显,这些实例没有您刚刚学到的新字段,所以修改了类,即使通过一些令人难以置信的扭曲这是可行的,不会那么有用;-).