如何在不触发“cgo result has Go pointer”的情况下在Go中包装C指针

2024-06-16 10:02:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试在cgo中实现一个函数,该函数将^{{cd1>}数组包装在^{{cd2>}:

//export ArrayToSlice
func ArrayToSlice(a *C.double, length int) (*[]float64) {
    hdr := reflect.SliceHeader{
        Data: uintptr(unsafe.Pointer(a)),
        Len:  length,
        Cap:  length,
    }
    return (*[]float64)(unsafe.Pointer(&hdr))
}

此函数应该是called from C, return the Slice to C, which will then pass it to another Go function

这以前用于Go 1.5,但在1.6中,它开始显示这种恐慌:

^{pr2}$

我理解问题是:Go不想向C分发指针,因为Go是垃圾收集的,并且可能会破坏非垃圾收集的C代码手中的指针。

有办法在1.6分内完成这一点吗?


Tags: to函数goreturnhdr数组length垃圾