如何使用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))]
>>>
更多内容
要在方法中引用类
,您可以执行以下操作:
# Don't do:
class Node:
Node
# But:
class Node:
def __init__(self):
type(self)
当你想从类内部使用类型提示时,你必须这样做:
from __future__ import annotations
关于python - ctypes中的循环结构,python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71618140/