python ctype递归结构 [英] python ctype recursive structures

查看:371
本文介绍了python ctype递归结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我已经开发了一个用于C的驱动程序的DLL。我用C ++编写了一个测试程序,并且DLL工作正常。这个DLL使用Python。我已经成功地隐藏了大多数用户定义的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))]


I've developped a DLL for a driver in C. I wrote a test program in C++ and the DLL works fine.

Now I'd like to interract with this DLL using Python. I've successfully hidden most of the user defined C structures but there is one point where I have to use C structures. I'm rather new to python so I may get things wrong.

My approach is to redefine a few structures in python using ctype then pass the variable to my DLL. However in these class I have a custom linked list which contains recursive types as follow

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

This fails, because inside EthercatDatagram, EthercatDatagram is not already defined so the parser returns an error.

How should I represent this linked list in python so that my DLL understands it correctly?

解决方案

You almost certainly want to declare next_command as a pointer. Having a structure that contains itself isn't possible (in any language).

I think this is what you want:

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递归结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆