python ctype 递归结构

标签 python dll recursion structure ctypes

我用 C 语言为驱动程序开发了一个 DLL。我用 C++ 编写了一个测试程序,该 DLL 工作正常。

现在我想使用 Python 与这个 DLL 进行交互。我已经成功隐藏了大部分用户定义的 C 结构,但有一点我必须使用 C 结构。我对 python 还很陌生,所以我可能会出错。

我的方法是使用 ctype 在 python 中重新定义一些结构,然后将变量传递给我的 DLL。然而,在这些类中,我有一个自定义链表,其中包含递归类型,如下所示

class EthercatDatagram(Structure):
    _fields_ = [("header", EthercatDatagramHeader),
                ("packet_data_length", c_int),
                ("packet_data", c_char_p),
                ("work_count", c_ushort),
                ("next_command", EthercatDatagram)]

这会失败,因为在 EthercatDatagram 内部,EthercatDatagram 尚未定义,因此解析器返回错误。

我应该如何在 python 中表示这个链表,以便我的 DLL 正确理解它?

最佳答案

您几乎肯定希望将 next_command 声明为指针。拥有包含自身的结构是不可能的(在任何语言中)。

我想这就是你想要的:

class EthercatDatagram(Structure):
    pass
EthercatDatagram._fields_ = [
    ("header", EthercatDatagramHeader),
    ("packet_data_length", c_int),
    ("packet_data", c_char_p),
    ("work_count", c_ushort),
    ("next_command", POINTER(EthercatDatagram))]

关于python ctype 递归结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28879604/

相关文章:

.net - 如何防止我的 .Net dll 被添加为引用?

optimization - void 返回类型函数的尾调用优化

php - 不递归打印数据

list - 如果嵌套列表有 1 个元素,如何删除 Scheme 中嵌套列表中的括号?

python - 如果我使用 QT For Windows,我的应用程序会在 Linux/Mac/Windows 上运行良好吗?

python - 如何在 Python 中评估集合中的两个或多个元素

c - typedef 解决 dll 包装器问题

c++ - msvcr90.dll 有时间戳吗?

python - 我如何计算不同 2D 向量行之间的 L2 或欧几里德距离

python - 计算给定情况的路径