如何更改类[python]中的ctypes字段大小?

2024-10-02 04:23:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用python解析来自网络的输入包。在

为此,我创建了一个简单的类:

class S2C_ChallengePacket(ctypes.Structure):
    _pack_ = 1
    _fields_ = [
    ("type", ctypes.c_byte),
    ("sessionid", ctypes.c_byte * 4),
    ("challenge", ctypes.c_wchar_p)]

字段“challenge”它是以null结尾的字符串,它的大小是可变的(可变的)。所以我把pack变量添加到我的s2chullengepacket类中。在

Python's documentation

pack An optional small integer that allows to override the alignment of structure fields in the instance. pack must already be defined when fields is assigned, otherwise it will have no effect.

但是,如果我尝试引用“challenge”字段,就会得到一个“Segmentation fault”错误。在

^{pr2}$

Tags: the网络fieldstypebytectypesstructurepack
1条回答
网友
1楼 · 发布于 2024-10-02 04:23:29

c_wchar_p是一个指针,因此它不起作用。使用struct模块会更容易:

>>> base_size = struct.calcsize('>BI')
>>> response = b'\x09\x00\x00\x00\x019513307\x00'
>>> response = response[:-1] # remove null
>>> token_len = len(response) - base_size
>>> struct.unpack('>BI%ds' % token_len, response)
(9, 1, b'9513307')

相关问题 更多 >

    热门问题