go - 在 Go 中读取 C 编写的二进制文件

标签 go

读取由 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/

相关文章:

networking - golang中获取SSID/其他网络信息

forms - Golang http : multiple response. WriteHeader 调用

go - 构建 Go Lang 数据库 'tiedot'

go - 如何将sql输出格式化为json

http - 在 golang net/http 中处理 TLSNextProto 的正确方法是什么?

pointers - 戈朗 : returning pointers and derefrencing

http - 你如何使用 Go 和 http 包删除 cookie?

go - 读取Go命令行程序中管道输入的长度

Javascript fetch() 不止一次 ping 我的 golang 休息端点?

go - 协议(protocol) : Go package has inconsistent package names