How to write struct to file in go or python?

huangapple go评论86阅读模式
英文:

How to write struct to file in go or python?

问题

在Go语言中,可以使用encoding/binary包将结构体写入文件。以下是一个示例代码:

package main

import (
	"encoding/binary"
	"os"
)

type mystruct struct {
	i   int32
	cha byte
}

func main() {
	file, err := os.Create("TEST.bin")
	if err != nil {
		panic(err)
	}
	defer file.Close()

	s := mystruct{
		i:   0,
		cha: 'A',
	}

	err = binary.Write(file, binary.LittleEndian, &s)
	if err != nil {
		panic(err)
	}
}

在Python中,可以使用struct模块将结构体写入文件。以下是一个示例代码:

import struct

class MyStruct:
    def __init__(self, i, cha):
        self.i = i
        self.cha = cha

s = MyStruct(0, b'A')

with open('TEST.bin', 'wb') as file:
    file.write(struct.pack('ci', s.i, s.cha))

这些示例代码将结构体以二进制形式写入文件,确保数据是连续的。在Go中使用encoding/binary包,而在Python中使用struct模块。

英文:

In C/C++, we can write a struct to file like this:

#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;
}

But how to wirte a struct to file in go or python ? I want the data in struct are continuous.

答案1

得分: 3

在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'表示一个整数后跟一个字符):

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

英文:

In Python you can use ctypes module which allows you to generate structures with similar layout as C does, and convert them to byte arrays:

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))

There is a simplest approach in Python with using struct.pack and manually provide a layout as first argument ('ic' means int followed by a char):

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

Go can encode structs via encoding/binary

type myStruct struct {
    i int 
    cha byte
}

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

NOTE: You will be subject of differing structure alignment, padding and endianness, so if you want to build truly interoperable program, use special formats such as Google Protobuf

huangapple
  • 本文由 发表于 2017年9月10日 17:25:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/46139165.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定