导出函数返回双精度数组 [英] Export function that returns array of doubles

查看:84
本文介绍了导出函数返回双精度数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Golang中如何导出返回双精度数组的函数.以前可能的方式似乎现在返回运行时错误:cgo结果具有Go指针":

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

推荐答案

为了安全地将指针存储在C中,它指向的数据必须在C中分配.

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

这篇关于导出函数返回双精度数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆