cgo:如何从c传递结构数组 [英] cgo: How to pass struct array from c to go

查看:125
本文介绍了cgo:如何从c传递结构数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C部分:

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

转到部分:

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

我可以通过这种方式获取数组的第一个元素.但是如何获得带有n个元素的整个数组呢? 以及如何安全地释放它们?

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?

推荐答案

首先,即使您使用的是Go语言,添加cgo时也不会再有安全"字样.由您决定何时以及如何释放内存,就像在C语言中进行编程一样.

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.

在go中使用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]

实际上没有分配最大大小的数组,但是Go需要恒定大小的数组,并且1<<30将足够大.将该数组立即转换为切片,并正确设置其长度和容量.

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.

这篇关于cgo:如何从c传递结构数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆