2017-12-01 2 views
0

C가 작성한 이진 파일을 읽는 적절한 방법은 무엇입니까? C 헤더 파일을 가지고 있는데, 구조체가 있습니다. Go에서 수동으로 다시 쓰는 대신이 헤더 파일을 사용할 수 있습니까? 여기C가 작성한 이진 파일 읽기

/* 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; 

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 
    // } 
} 
+2

[cgo] (https://golang.org/cmd/cgo/)가 도움이 될 수 있습니다. – kichik

+2

@kichik : OP가 이미 cgo를 사용하고 있다는 질문에서 나타납니다. – ruakh

답변

1

하는 https://golang.org/pkg/encoding/binary/

당신은 이동 구조체로 읽을 binary.Read을 사용할 수 있습니다에서 당신이 찾을 수있는 encoding/binary 패키지를 사용하여 읽기 의사 코드 내 시작 이동 프로그램입니다. C 버전이 추가 할 패딩을 고려해야합니다. 귀하의 예제에서 기본 패딩은 createTime 앞에 2 개의 패드 바이트를 넣습니다.