在Golang中如何导出返回双精度数组的函数。以前的方式似乎返回“运行时错误:cgo结果有Go指针”现在:
//export Init
func Init(filename string) (C.int, unsafe.Pointer) {
var doubles [10]float64
doubles[3] = 1.5
return 10, unsafe.Pointer(&doubles[0])
}
答案 0 :(得分:2)
为了在C中安全地存储指针,它指向的数据必须在C中分配。
//export Init
func Init(f string) (C.size_t, *C.double) {
size := 10
// allocate the *C.double array
p := C.malloc(C.size_t(size) * C.size_t(unsafe.Sizeof(C.double(0))))
// convert the pointer to a go slice so we can index it
doubles := (*[1<<30 - 1]C.double)(p)[:size:size]
doubles[3] = C.double(1.5)
return C.size_t(size), (*C.double)(p)
}