Ctypes结构终结

2024-09-20 22:53:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个动态结构类。ctypes结构的问题是,在初始化结构或设置字段时,会发生终结过程。你知道吗

在ctypes源的test scripts中,我发现:

Structure/Union classes must get 'finalized' sooner or later, when one of these things happen:

  1. _fields_ is set.
  2. An instance is created.
  3. The type is used as field of another Structure/Union.
  4. The type is subclassed

When they are finalized, assigning fields is no longer allowed.

结构用于函数指针。在Structure的子类中,我定义了helper函数,它用应该在\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\。你知道吗

这将允许我的脚本用户创建一个结构,而无需使用以下内容对其进行子类化:

class Sub (Structure)
    _fields_ = [
        (<func_name>, CFUNCTYPE(<res>,<*args>)),
        (...),
        ]

Sub(CFUNCTYPE(<res>, <*args>)(<func_impl>), ...)

但应使用:

class Sub(function_struct):
    pass

Sub.addFunction(...)
Sub(<func_impl>)

在我的子类的init函数中,我设置了\u fields\u属性,它应该完成类型。但是,在uuu init_uuu函数中添加的字段不会显示为属性。给我像'Sub' object has no attribute '<func_name>'这样的错误

我怀疑子类在#u init#调用之前已经完成,通过我列表中的#2或#4。你知道吗

是否有任何方法可以绕过终结或延迟它,以便我动态设置\u fields\u属性?你知道吗


Tags: of函数fields属性initis动态ctypes
1条回答
网友
1楼 · 发布于 2024-09-20 22:53:39

我通过制作一个工厂类来解决我的问题。你知道吗

factory = structFactory()
factory.addFunction(<name>, <rtype>)

# Also redefines the __init__ function before returning the type
structType = factory.getType() 

struct = structType(<impl>)

也可以从具有ctypes.caststructType.from_address的内存地址创建结构。你知道吗

相关问题 更多 >

    热门问题