go - 如何将 C.double 数组传递给 Cgo 函数?

标签 go cgo

我刚刚开始使用 CGo,我正在尝试将数据发送到 C 库,该库对 float / double 组执行统计计算。我现在想弄清楚的是如何将一组 float 或 C.double 发送到具有如下签名的 CGo 函数:

double pop_mean(int numPoints, double a[])

我已经想出了如何进入 C.int 的方法,但我无法弄清楚如何发送 double 组。

我还没有看到任何关于这件事的博客文章或 SO 问题,所以我想我会问。

以下是我迄今为止的最大努力。

// Get a basic function to work, while passing in an ARRAY  arr := make([]C.double, 0)
arr = append(arr, C.double(10.0))
arr = append(arr, C.double(20.0))
arr = append(arr, C.double(30.0))
var fixedArray [3]C.double = arr[:]

// ptr := C.CBytes(arr)
// defer C.free(unsafe.Pointer(ptr))

coolMean := C.pop_mean(3, &fixedArray)
fmt.Println("pop_mean (10, 20, 30): ", coolMean)

这是我遇到的错误:

./main.go:64:6: cannot use arr[:] (type []_Ctype_double) as type [3]_Ctype_double in assignment
./main.go:69:35: cannot use &fixedArray (type *[3]_Ctype_double) as type *_Ctype_double in argument to _Cfunc_pop_mean

我应该如何将 C.double 数组传递给代码?

最佳答案

When an array name is passed to a function, what is passed is the location of the initial element. Within the called function, this argument is a local variable, and so an array name parameter is a pointer, that is, a variable containing an address.

C Programming Language, 2nd Edition


Slice types

A slice is a descriptor for a contiguous segment of an underlying array and provides access to a numbered sequence of elements from that array.

Like arrays, slices are indexable and have a length. The length of a slice s can be discovered by the built-in function len; unlike with arrays it may change during execution. The elements can be addressed by integer indices 0 through len(s)-1. The slice index of a given element may be less than the index of the same element in the underlying array.

A slice, once initialized, is always associated with an underlying array that holds its elements.

The Go Programming Language Specification


Reference: Go Command cgo


对于 slice apop_mean(int numPoints, double a[]) C 函数的参数是 len(a) , slice 底层数组的长度,&a[0], slice 底层数组的第一个元素的地址。


在 Go 中,我们经常将细节隐藏在函数中。例如,popMean 函数,

package main

import (
    "fmt"
)

/*
double pop_mean(int numPoints, double a[]) {
    if (a == NULL || numPoints == 0) {
        return 0;
    }
    double mean = 0;
    for (int i = 0; i < numPoints; i++) {
        mean+=a[i];
    }
    return mean / numPoints;
}
*/
import "C"

func popMean(a []float64) float64 {
    // This is the general case, which includes the special cases
    // of zero-value (a == nil and len(a) == 0)
    // and zero-length (len(a) == 0) slices.
    if len(a) == 0 {
        return 0
    }
    return float64(C.pop_mean(C.int(len(a)), (*C.double)(&a[0])))
}

func main() {
    a := make([]float64, 10)
    for i := range a {
        a[i] = float64(i + 1)
    }

    // slice
    fmt.Println(len(a), a)
    pm := popMean(a)
    fmt.Println(pm)

    // subslice
    b := a[1:4]
    fmt.Println(len(b), b)
    pm = popMean(b)
    fmt.Println(pm)

    // zero length
    c := a[:0]
    fmt.Println(len(c), c)
    pm = popMean(c)
    fmt.Println(pm)

    // zero value (nil)
    var z []float64
    fmt.Println(len(z), z, z == nil)
    pm = popMean(z)
    fmt.Println(pm)
}

输出:

10 [1 2 3 4 5 6 7 8 9 10]
5.5
3 [2 3 4]
3
0 []
0
0 [] true
0

关于go - 如何将 C.double 数组传递给 Cgo 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53549475/

相关文章:

loops - 在 GO 模板中使用 range over struct

GO zip.NewWriter() 创建空的 zip 文件

go-routines 和 channels in go

c++ - Cgo 找不到像 <iostream> 这样的标准库

用 Golang 和 C 编写的 Python 模块

mongodb - 创建 session : no reachable servers - mgo

go - 为什么允许 "const true = false"?

go - cgo:将 `[]uchar`转换为 `[]byte`

pointers - 戈朗 Cgo : panic: runtime error: cgo argument has Go pointer to Go pointer

go - golang的cgo中如何使用std::vector或者其他容器?