cgo: How to pass struct array from c to go

前端 未结 1 782
执念已碎
执念已碎 2020-12-03 15:55

The C part:

struct Person {...}
struct Person * get_team(int * n)

The Go part:

n := C.int(0)
var team *C.struct_Person = C.         


        
相关标签:
1条回答
  • 2020-12-03 16:41

    First, even though you’re using Go, when you add cgo there is no longer any "safe". It's up to you to determine when and how you free the memory, just as if you were programming in C.

    The easiest way to use a C array in go is to convert it to a slice through an array:

    team := C.get_team()
    defer C.free(unsafe.Pointer(team))
    teamSlice := (*[1 << 30]C.struct_Person)(unsafe.Pointer(team))[:teamSize:teamSize]
    

    The max-sized array isn't actually allocated, but Go requires constant size arrays, and 1<<30 is going to be large enough. That array is immediately converted to a slice, with the length and capacity properly set.

    0 讨论(0)
提交回复
热议问题