Export function that returns array of doubles

风流意气都作罢 提交于 2019-12-02 10:57:48

问题


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)
}


来源:https://stackoverflow.com/questions/43330938/export-function-that-returns-array-of-doubles

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!