ctypes 与 python 数据类型间的互转问题

文章介绍了如何在Python中使用ctypes库将结构体(如C_class1)转换为bytes,以及如何将bytes数据恢复为ctypes结构体。通过定义_structure_,设置_pack_属性,使用memmove函数进行内存操作,实现了二进制数据的相互转换。
摘要由CSDN通过智能技术生成

参考链接

如何将 python数据类型按照 ctypes 类型转换位 bytes

from ctypes import *

class C_class1(Structure):
    _pack_ = 1

    _fields_ = [('value', c_byte)]


cmd = C_class1()
cmd.value = -2
ret = (c_byte * sizeof(cmd))()
memmove(addressof(ret), addressof(cmd), sizeof(cmd))
print(bytearray(ret))
# bytearray(b'\xfe')

如何将 bytes 按照 ctypes 类型转换为 python 数据类型

from ctypes import *

class C_class1(Structure):
    _pack_ = 1

    _fields_ = [('value', c_byte)]

b_arr = bytearray(b'\xfe')
cmd = C_class1()
ctypes_arr = (c_byte * sizeof(cmd)).from_buffer(b_arr) # 返回一个共享 source 对象缓冲区的 ctypes 实例
memmove(addressof(cmd), addressof(ctypes_arr), sizeof(cmd))
print(cmd.value)
# -2
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值