读取C编写的二进制文件的正确方法是什么? 我有一个C头文件,有一些'结构'。 是否可以使用这些头文件而不是手动在Go中重写它们。
/* sample.h */
#define HEADER_SIZE 2048 //* large then sizeof(header)
typedef struct {
uint8_t version;
uint8_t endian;
uint32_t createTime;
} header;
typedef struct {
uint64_t data1;
uint32_t data2;
char name[128];
} record;
这是我使用伪代码开始的Go程序
package "main"
// #include "sample.h"
import "C"
func main() {
f, _ := os.Open("sample_file")
// read(buf, HEADER_SIZE) and print out
// use structure header to decode the buf
// while not end of file {
// read(buf, sizeof(record) and print out
// }
}
答案 0 :(得分:1)
使用您在https://golang.org/pkg/encoding/binary/
找到的encoding/binary
包阅读它们
您可以使用binary.Read
读取Go结构。您需要考虑C版本将添加的填充。在您的示例中,默认填充将在createTime
之前放置2个填充字节。