Python ctypes与io.读入没有

2024-06-12 19:02:52 发布

您现在位置:Python中文网/ 问答频道 /正文

当我用ctypes读取二进制数据时,它不能正常工作。在

二进制数据

03 00 00 00 49 7B 00 00 00 00 00 00

python代码

^{pr2}$

结果

3
0

但是当我读到二进制数据blow并取消对python代码的注释时,它工作得很好。在

03 00 00 00 03 00 00 00 49 7B 00 00 00 00 00 00

结果

3
3
31561

好像是只虫子。有人能帮我解决这个问题吗? 任何建议都将不胜感激。在

环境: Windows 7 x64 Python 2.7 x32 ctypes 1.1.0版


Tags: 数据代码环境windows二进制ctypes建议虫子
1条回答
网友
1楼 · 发布于 2024-06-12 19:02:52

据我所知,你在structure packing上有问题。看起来您的代码读取的是“03 00 00 00 49 7B 00 00”(字大小为64位),但只使用前4个字节“03 00 00 00”。在

更新:根据eryksun,上述分析是正确的。只需在DataStructure的定义中设置_pack_ = 1。在

一些人在尝试C代码:

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

struct data_structure {
    uint32_t long1;
    uint64_t longlong;
};

int main(int argc, char const *argv[])
{
    FILE *fd, *other_fd;
    struct data_structure my_struct;

    my_struct.long1 = 3;
    my_struct.longlong = 31561;

    fd = fopen("ULongLong", "wb");
    if (!fd)
    {
        printf("Unable to open file!");
        return 1;
    }

    fwrite(&my_struct, sizeof(struct data_structure), 1, fd);
    fclose(fd);
    exit(0);
}

编译并运行后,检查了ULongLong文件:

^{pr2}$

有时您会在第5到第8字节中得到一些垃圾:

$ hexdump ULongLong
00000000 0300 0000 ff7f 0000  497b 0000 0000 0000
00000010

$ hexdump ULongLong
0000000 0003 0000 7fff 0000 7b49 0000 0000 0000
0000010

这个二进制文件正确吗?

相关问题 更多 >