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

标签 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

我想对其进行编码,然后将其存储在一个变量中.....那我该怎么做呢???

最佳答案

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

fileobj.write(my_c_structure).

然后您可以通过打开文件并执行以下操作来重新加载它

my_c_structure = MyCStructure()
fileobj.readinto(my_c_structure)

您所需要的只是使您的 __init__ 参数可选。参见 this post on Binary IO .它解释了如何通过套接字或使用 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 也不是虽然它会工作。只是更复杂。

编辑:另请参阅 How to pack and unpack using ctypes (Structure <-> str) 处的链接答案另一种方法。

编辑 2:参见 http://doughellmann.com/PyMOTW/structhttp://effbot.org/librarybook/struct.htm用于结构示例。

关于python - 在 Python 中获取 ctypes 结构的二进制表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7021841/

相关文章:

python - 在数据库中存储 700 万个键的 python 字典

python - 了解创建守护进程的Python代码

在 C 中创建具有邻接矩阵的图

python - 如何将类对象传递给 ctypes.windll.LoadLibrary(DLL) 函数?

python - 使用 Python ctypes 运行 C dll 函数时出现问题(未知大小的数组输出)

python - Salesforce REST API 注销

python - Keras/NN - 处理 NaN、缺少输入

c - C中结构体数组的排序

matlab - 获取结构的第 n 个字段

python - 将 ctypes 结构传递给 cython