cgo: How to pass struct array from c to go

╄→尐↘猪︶ㄣ 提交于 2019-11-28 05:18:34

问题


The C part:

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

The Go part:

n := C.int(0)
var team *C.struct_Person = C.get_team(&n)
defer C.free(unsafe.Pointer(team))

I can get the first element of the array in this way. But how to get the whole array with n elements? and how to free them safely?


回答1:


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.



来源:https://stackoverflow.com/questions/28925179/cgo-how-to-pass-struct-array-from-c-to-go

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!