获取Python中ctypes结构的二进制表示

3 投票
1 回答
3590 浏览
提问于 2025-04-16 23:21

我想给一条信息进行编码……这是我生成的信息

from ctypes import memmove, addressof, Structure, c_uint16,c_bool

class AC(Structure):
    _fields_ = [("UARFCN",  c_uint16),
                 ("ValidUARFCN", c_bool ),("PassiveActivationTime", c_uint16) ]

    def __init__(self , UARFCN ,ValidUARFCN , PassiveActivationTime):
            self.UARFCN                 =    UARFCN
            self.ValidUARFCN            =    True
            self.PassiveActivationTime  =    PassiveActivationTime

    def __str__(self):
        s = "AC"
        s += "UARFCN:"  + str(self.UARFCN)
        s += "ValidUARFCN"  + str(self.ValidUARFCN)
        s += "PassiveActivationTime"  +str(self.PassiveActivationTime)
        return s

class ABCD(AC):
        a1 = AC( 0xADFC , True , 2)
        a2 = AC( 13 , False ,5)
        print a1
        print a2

我想把它编码后存储在一个变量里……那我该怎么做呢???

1 个回答

4

对于C语言的结构体,写入文件的步骤很简单:先打开文件,然后执行

fileobj.write(my_c_structure).

接着,你可以通过打开文件来重新加载它,执行

my_c_structure = MyCStructure()
fileobj.readinto(my_c_structure)

你只需要把你的 __init__ 参数设为可选的。可以参考这篇关于二进制输入输出的文章,它讲解了如何通过套接字或者使用 multiprocessing 的监听器来发送 Structure

如果想把它保存为字符串或字节,只需执行

from io import BytesIO # Or StringIO on old Pythons, they are the same
fakefile = BytesIO()
fakefile.write(my_c_structure)
my_encoded_c_struct = fakefile.getvalue()

然后用下面的方式读取出来

from io import BytesIO # Or StringIO on old Pythons, they are the same
fakefile = BytesIO(my_encoded_c_struct)
my_c_structure = MyCStructure()
fakefile.readinto(my_c_structure)

其实不需要使用Pickle等工具,也不一定要用struct.pack,虽然这样也能工作,但会更复杂。

补充:还可以查看如何使用ctypes进行打包和解包,这是一种实现这个功能的另一种方法。

补充2:可以参考http://doughellmann.com/PyMOTW/structhttp://effbot.org/librarybook/struct.htm,里面有关于结构体的例子。

撰写回答