私はそのようなことをしたい:
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'>