有没有可能创建间接递归的ctypes.结构类型?

2024-04-25 19:21:29 发布

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

这与#1228158#28879604不同。这很相似,但有一个转折点。你知道吗

创建引用自己类型的递归类型很简单:

A = type('A', (ctypes.Structure,), {})
A._fields_ = [('another_a', ctypes.POINTER(A))]

或者,如果您愿意:

class A(ctypes.Structure):
    pass
A._fields_ = [('another_a', ctypes.POINTER(A))]

同样的事情。如果他们不是同一件事,一定要教育我!你知道吗

但是我正在尝试将Cstructs和typedefs机器翻译成ctypes.Structures。我希望Python端的名称和关系反映C端的名称和关系。如果函数返回一个uint32,即typedef作为consumer_id,我希望Python端的对象具有更具描述性的名称。现在,有一种情况经常发生:

typedef dummy_type official_type;
typedef struct dummy_struct {
    official_type *another_struct;
} dummy_type;

无论我如何扭曲和扭转,我都无法在Python中实现这种关系。中间名可能在任何地方都没有使用,所以目前我们的想法是检测这种情况并使official_type成为ctypes.Structure指代自身。可能会使dummy_typestruct dummy_struct类型引用它们自己。在二进制级别上,在C端,它们都是等价的。你知道吗

但我真正想做的是:

Struct_dummy_struct = type('struct_dummy_struct', (ctypes.Structure,), {})
Dummy_type = type('dummy_type', (Struct_dummy_struct,), {})
Official_type = type('official_type', (Dummy_type,), {})
Struct_dummy_struct._fields_ = [('another_struct', ctypes.POINTER(Official_type))]

当然,这是不可能的:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: _fields_ is final

我认为我想做的理论上是不可能的,考虑到ctypes的工作方式,但是如果有人能告诉我有办法,我会很高兴的!你知道吗


Tags: 名称类型fields关系typeanother情况ctypes
1条回答
网友
1楼 · 发布于 2024-04-25 19:21:29

在python中不需要相同的构造:

class official_type(ctypes.Structure):
    pass
official_type._fields_ = [("another_struct", ctypes.POINTER(official_type))]
first_instance = official_type()
second_instance = official_type()
first_instance.another_struct = ctypes.pointer(second_instance)
print first_instance.another_struct

<__main__.LP_official_type object at ...>

Ctypes有一个时髦的结构终结过程,如果深入研究单元测试,您会发现如下内容:

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.

也许使用类型的类定义会把过程搞砸。你知道吗

相关问题 更多 >