python ctype recursive structures

后端 未结 3 1591
一向
一向 2020-11-30 11:53

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 successf

相关标签:
3条回答
  • 2020-11-30 12:01

    You'll have to access _fields_ statically after you've created it.

    class EthercatDatagram(Structure)
      _fields_ = [...]
    
    EthercatDatagram._fields_.append(("next_command", EthercatDatagram))
    
    0 讨论(0)
  • 2020-11-30 12:11

    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))]
    
    0 讨论(0)
  • 2020-11-30 12:14

    The reason why

    EthercatDatagram._fields_.append(("next_command", EthercatDatagram))
    

    does not work is that the machinery that creates the descriptor objects (see the source of the PyCStructType_setattro function) for accessing the next_command attribute is activated only upon assignment to the _fields_ attribute of the class. Merely appending the new field to the list goes completely unnoticed.

    To avoid this pitfall, use always a tuple (and not a list) as the value of the _fields_ attribute: that will make it clear that you have to assign a new value to the attribute and not modify it in place.

    0 讨论(0)
提交回复
热议问题