读取由 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
// }
}
最佳答案
使用您可以在 https://golang.org/pkg/encoding/binary/ 找到的 encoding/binary
包阅读它们
您可以使用 binary.Read
读入 Go 结构。您需要考虑 C 版本将添加的填充。在您的示例中,默认填充会在 createTime
之前放置 2 个填充字节。
关于go - 在 Go 中读取 C 编写的二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47585712/