Export function that returns array of doubles

2020-04-22 04:38发布

问题:

In Golang how to export the function that returns array of doubles. The way it was possible before seems to return "runtime error: cgo result has Go pointer" now:

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

回答1:

In order to safely store a pointer in C, the data it points to must be allocated in 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)
}


标签: go cgo