returns 双精度数组的导出函数

Export function that returns array of doubles

在 Golang 中如何导出 returns array of double 的函数。以前可能的方式现在看来 return "runtime error: cgo result has Go pointer":

//export Init
func Init(filename string) (C.int, unsafe.Pointer) {
    var doubles [10]float64
    doubles[3] = 1.5
    return 10, unsafe.Pointer(&doubles[0])
}

为了在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)
}