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

时间:2011-08-11 06:40:31

标签: python struct ctypes

我想编码一条消息......这是我生成的消息

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 个答案:

答案 0 :(得分:4)

对于C结构,要将其写入文件所需要做的就是打开文件,然后执行

fileobj.write(my_c_structure).

然后你可以通过打开文件并执行

来重新加载它
my_c_structure = MyCStructure()
fileobj.readinto(my_c_structure)

您只需要使__init__个参数可选。见this post on Binary IO。它解释了如何通过套接字或Structure监听器发送multiprocessing

要将其保存在字符串/字节中,只需执行

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)

泡菜等不是必需的。虽然它会起作用,但struct.pack都不是。它更复杂。

修改:还可以在How to pack and unpack using ctypes (Structure <-> str)查看链接的答案,了解另一种方法。

编辑2:有关结构示例,请参阅http://doughellmann.com/PyMOTW/structhttp://effbot.org/librarybook/struct.htm