python - 如何在go或python中将结构写入文件?

标签 python go

在C/C++中,我们可以这样写一个结构体到文件:

#include <stdio.h>
struct mystruct
{
    int i;
    char cha;
};

int main(void)
{
    FILE *stream;
    struct mystruct s;
    stream = fopen("TEST.$$$", "wb"))
    s.i = 0;
    s.cha = 'A';
    fwrite(&s, sizeof(s), 1, stream); 
    fclose(stream); 
    return 0;
}

但是如何将结构写入 go 或 python 中?我希望结构中的数据是连续的。

最佳答案

在 Python 中,您可以使用 ctypes 模块,它允许您生成具有与 C 类似布局的结构,并将它们转换为字节数组:

import ctypes

class MyStruct(ctypes.Structure):
    _fields_ = [('i', ctypes.c_int),
                ('cha', ctypes.c_char)]

s = MyStruct()
s.i = 0
s.cha = 'A'

f.write(bytearray(s))

Python 中有一个最简单的方法,使用 struct.pack 并手动提供布局作为第一个参数('ic' 表示 int后跟一个字符):

import struct 
f.write(struct.pack('ic', 0, 'A'))

Go 可以通过 encoding/binary 对结构体进行编码

type myStruct struct {
    i int 
    cha byte
}

s := myStruct{i: 0, cha:'A'}
binary.Write(f, binary.LittleEndian, &s)

注意:您将受到不同结构对齐方式填充字节顺序的影响,所以如果您想要要构建真正可互操作的程序,请使用特殊格式,例如 Google Protobuf

关于python - 如何在go或python中将结构写入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46139165/

相关文章:

python - 属性错误: 'AnonymousUserMixin' object has no attribute 'can'

go - 尝试在Go中设置Cookie,但收到一条CORS错误,指出Access-Control-Allow-Credentials未设置为true

unit-testing - 如何测试永远循环的代码

go - 从 strings.Replace() Golang 倒置返回

golang接口(interface) "used as value"错误

python - 使用 python3 在 vi​​rtualenv 中设置环境卡在 setuptools、pip、wheel

python - 组合 pandas 数据框中的列

仅当时间是整点后 5 点时才使用 Python

python - 导入 pygame 没有名为 'pygame' 的模块

图像 blob 到 base64