ctypes 中的循环结构,python

circular struct in ctypes, python

如何使用 ctypes 在 python 中表示循环 struct

一个链表在c中可以用下面的方式表示

typedef struct LinkedList LinkedList;
typedef struct Node Node;

struct Node
{
    int value;
    Node* next;
};


struct LinkedList
{
    Node* start;
    int length;
};

如何使用 ctypes 在 python 中表示相同的 struct。 我尝试了以下

from ctypes import *


class Node(Structure):
    _fields_ = [
        ("value", c_int),
        ("next", pointer(Node))
    ]

但是上面给出了如下错误

NameError: name 'Node' is not defined

你应该阅读 ctypes 的文档,在那里你会发现:

>>> from ctypes import *
>>> class cell(Structure):
...     pass
...
>>> cell._fields_ = [("name", c_char_p),
...                  ("next", POINTER(cell))]
>>>

更多


要在方法中引用 class,您可以这样做:

# Don't do:
class Node:
    Node
# But:
class Node:
    def __init__(self):
        type(self)

当你想从内部对 class 使用类型提示时,你必须这样做:

from __future__ import annotations