英文:
Export function that returns array of doubles
问题
在Golang中,如何导出返回双精度数组的函数。之前的方法似乎现在返回"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])
}
请注意,我只提供了代码的翻译部分。
英文:
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
得分: 3
为了在C语言中安全地存储指针,指针所指向的数据必须在C语言中进行分配。
// 导出 Init 函数
func Init(f string) (C.size_t, *C.double) {
size := 10
// 分配 *C.double 数组
p := C.malloc(C.size_t(size) * C.size_t(unsafe.Sizeof(C.double(0))))
// 将指针转换为Go切片,以便我们可以对其进行索引
doubles := (*[1<<30 - 1]C.double)(p)[:size:size]
doubles[3] = C.double(1.5)
return C.size_t(size), (*C.double)(p)
}
英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论