导出返回双精度数组的函数。

huangapple go评论94阅读模式
英文:

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&lt;&lt;30 - 1]C.double)(p)[:size:size]
	doubles[3] = C.double(1.5)

	return C.size_t(size), (*C.double)(p)
}

huangapple
  • 本文由 发表于 2017年4月11日 02:56:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/43330938.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定