我用 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/