我想做这样的事情:
from ctypes import *
class Packet(BigEndianStructure):
_fields_ = [("length", c_ushort),
("session", c_uint),
("command", c_ushort)]
class PacketString(BigEndianStructure):
_fields_ = [("length", c_ushort),
("value", c_char_p)]
class InitialPacket(Packet):
_fields_ = [("time", PacketString)]
但是我收到错误,因为 c_char_p 只能是本机字节顺序。但也许还有其他方法可以制作长度在它们之前指定的字符串。我只是喜欢结构很容易从套接字读取/写入。以及您如何定义 _fields_ 然后可以像这样使用它:
initialPacket = InitialPacket()
initialPacket.command = 128
问题是:如何在 BigEndianStructure 中创建可变长度字段?因为 Python 不允许我使用 c_char_p。脚本根本不会运行。这是错误:
Traceback (most recent call last):
File "C:\PKOEmu\test.py", line 8, in <module>
class PacketString(BigEndianStructure):
File "C:\Python27\lib\ctypes\_endian.py", line 34, in __setattr__
fields.append((name, _other_endian(typ)) + rest)
File "C:\Python27\lib\ctypes\_endian.py", line 24, in _other_endian
raise TypeError("This type does not support other endian: %s" % typ)
TypeError: This type does not support other endian: <class 'ctypes.c_char_p'>