python - ctypes中的循环结构,python

标签 python c struct

如何使用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/

相关文章:

c - 如何使用 strcpy 将字符串数组存储到结构中?

Python Proton 将二进制数据发送到 Active MQ

python - 使用 sudo 运行 Django 找不到已安装的 Homebrew 程序包

c++ - 访问另一个结构中的结构字段

C - 当单个链表中只有 1 个元素时删除节点

c - 想要构建只有一个内核和一个二进制文件的裸 Linux 系统

c - 将结构传递给多个其他函数

python - 使用 Python 进行内联 CSV 文件编辑

python - 如何从 Python 迭代器提供子进程的标准输入?

ruby-on-rails - 在 ruby​​ 进程之间处理大数据对象