go - What is the best way to share struct definition in C and Golang -


i’m trying send data c program golang. data representing raw c struct. i’m trying unmarshal in golang.

a sample this:

typedef struct taga {     int64_t a;     int64_t b;     char  c[1024]; }a; 

a method rewrite c struct golang struct. say:

type struct{     int64     b int64     c [1024]byte } 

and convert raw data byte stream using encoding/binary . using method, should maintain 2 different-interrelated structs.

another method use cgo, import c language head file(.h) contains struct, , use c.a , unsafe point convert raw data struct c.a. it’s somehow buggy, , i’m crashed convert c char array golang string.

what’s option? suggestion?

one way using cgo: may access fields of c struct, using var s *c.struct_taga = &c.n or using s := &c.n working sample code:

package main  /* #include <string.h> #include <stdint.h> typedef struct taga {     int64_t a;     int64_t b;     char  c[1024]; }a;  n={12,22,"test"}; */ import "c"  import "fmt"  type struct {     int64     b int64     c [1024]byte }  func main() {     s := &c.n // var s *c.struct_taga = &c.n      t := a{a: int64(s.a), b: int64(s.b)}     length := 0     i, v := range s.c {         t.c[i] = byte(v)         if v == 0 {             length =             break         }     }      fmt.println("len(s.c):", len(s.c)) // 1024     str := string(t.c[0:length])            fmt.printf("len:%d %q \n", len(str), str) // len:4 "test"       s.a *= 10     fmt.println(s.a) // 120  } 

output:

len(s.c): 1024 len:4 "test"  120 

you may use s.a , s.b , s.c directly in golang. not need copy of it.


Comments