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

3

我想加密一条信息…这是我生成的消息

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

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


4
你的意思是什么,"encode it"是什么意思?(将其翻译成中文) - agf
我不确定我完全理解你想要什么。但是如果我猜的对,你可以使用 from hashlib import md5md5(String_here).hexdigest() - Bogdan
如果我需要将这条消息发送给接收者,我会以编码形式发送它... - NOOB
@machine 他的意思是以内存中的表示形式发送它。这就是他在第一条评论中提到的packstruct.pack)的含义。 - agf
@机器:我不知道为什么你不明白我在说什么...很清楚啊...agf也提到了这个问题... - NOOB
显示剩余5条评论
1个回答

4
对于C结构体,您只需要打开文件,然后执行以下操作即可将其写入文件中。
fileobj.write(my_c_structure).

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

my_c_structure = MyCStructure()
fileobj.readinto(my_c_structure)

你只需将__init__参数设为可选项即可。请参阅有关二进制IO的帖子。它解释了如何通过套接字或multiprocessing Listeners发送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以获取关于结构示例的信息。

请参考 http://www.doughellmann.com/PyMOTW/struct/ 或者 http://effbot.org/librarybook/struct.htm 了解 struct 的示例。 - agf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接