Go/CGo-如何使用作为指针传递的C数组 [英] Go/CGo - how do you use a C array passed as a pointer
本文介绍了Go/CGo-如何使用作为指针传递的C数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我将其发布为问题/答案,因为这花了我一段时间才能解决,并且我不介意对我的解决方案提出任何反馈.在Go/CGo中,如何处理作为指针传递的C数组?
I'm posting this as a question/answer, as it took me a while to work out, and I wouldn't mind some feedback on my solution. In Go/CGo, how do you work with a C array passed as a pointer?
例如,使用此C结构:
struct _GNetSnmpVarBind {
guint32 *oid; /* name of the variable */
gsize oid_len; /* length of the name */
... and other fields
};
我想将oid字段转换为Go字符串,如何使用guint32 *指针?
I want to convert oid field to a Go string, how would I work with the guint32* pointer?
推荐答案
您可以使用未经测试,但希望您能理解!尽管切片直接指向切片,但不要让切片的寿命比C数据长.
Untested but hopefully you get the idea! Don't let the slice live longer than the C data though as it points directly into it.
上次使用此代码时,我查看了反汇编,它生成了非常有效的代码.
Last time I used this I had a look at the disassembly and it generates very efficient code.
func gIntArrayOidString(oid *_Ctype_guint32, oid_len _Ctype_gsize) (result string) {
var oids []uint32
sliceHeader := (*reflect.SliceHeader)((unsafe.Pointer(&oids)))
sliceHeader.Cap = oid_len
sliceHeader.Len = oid_len
sliceHeader.Data = uintptr(unsafe.Pointer(oid))
var result string
for _, value := range oids {
result += fmt.Sprintf(".%d", value)
}
return result[1:]
}
这篇关于Go/CGo-如何使用作为指针传递的C数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文