我有一个原始的二进制文件,我正试图将它转换/移动到我创建的ctypes结构中,但是我似乎找不到合适的命令来执行它。你知道吗
我的代码的简化版本:
class Example_Structure(Structure):
_fields_ = [
("a", c_uint16),
("b", c_uint16, 14),
("c", c_uint16, 2),
("d", c_uint16)
]
#reading a file using open() and getting file size
buf = create_string_buffer(file_size)
file_object.readinto(buf)
struct = Example_Structure()
memmove(addressof(struct),buf,48) #This is the line I'm unsure about
# Maybe use cast(buf,struct) ?
print(struct.a)
我通常在没有addressof(struct)
的情况下在memmove
行上得到"ArgumentError: argument 1: <type 'exceptions.TypeError'>: wrong type"
,但是使用addressof
只会为每个字段提供0
。你知道吗
谢谢你的帮助
编辑: 我发现了一些成功的方法:
tmp = cast(addressof(buf),POINTER(struct)).contents
比你想象的容易。
ctypes.Structure
支持缓冲区协议,因此您可以直接执行以下操作:示例:
输出:
我想你的建筑应该是64号。但你甚至不用猜。使用
sizeof
使memmove语句它的一个很好的特性是,如果您对Example\u结构中的字段进行了更改,就不必返回并计算大小。你知道吗
最后,我建议您将变量从struct重命名为其他名称。如果您决定使用流行的struct module that is built into the standard library,可能会遇到命名冲突的问题。你知道吗
相关问题 更多 >
编程相关推荐