【问题标题】:How do I pass an array of C.double's to a Cgo function?如何将 C.double 数组传递给 Cgo 函数?
【发布时间】:2018-11-30 23:52:31
【问题描述】:

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

double pop_mean(int numPoints, double a[])

我已经知道如何进入其中的 C.int,但我无法弄清楚如何发送一个双精度数组。

我还没有看到任何关于这个确切事情的博客文章或 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 数组传递给代码?

【问题讨论】:

    标签: go cgo


    【解决方案1】:

    当一个数组名被传递给一个函数时,传递的是 初始元素的位置。在被调用函数中,这个 参数是局部变量,因此数组名称参数是 指针,即包含地址的变量。

    C Programming Language, 2nd Edition


    Slice types

    切片是底层的连续段的描述符 数组并提供对该数组元素的编号序列的访问 数组。

    像数组一样,切片是可索引的并且有长度。一个长度 slice s 可以通过内置函数 len 发现;不像 数组在执行过程中可能会改变。可以解决的元素 通过整数索引 0 到 len(s)-1。给定的切片索引 元素可能小于相同元素的索引 底层数组。

    切片一旦初始化,总是与底层相关联 包含其元素的数组。

    The Go Programming Language Specification


    参考:Go Command cgo


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


    在 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
    

    【讨论】:

      【解决方案2】:

      我发现您必须发送指向数组中第一个值的指针,而不是发送指向切片的第一个元素或切片本身的指针。

      我还遇到了一个问题,我创建了一个新变量,该变量分配了切片中第一项的值,然后创建了一个指向该变量的指针(它不再是原始数组的一部分),而不是创建指向数组中第一项的指针(就像我想要的那样)。

      以下是工作代码,使用 cmets 可帮助避免上述段落中的问题。

      // Get a basic function to work, while passing in an ARRAY
      
      // Create a dummy array of (10,20,30), the mean of which is 20.
      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))
      firstValue := &(arr[0]) // this notation seems to be pretty important... Re-use this!
      // if you don't make it a pointer right away, then you make a whole new object in a different location, so the contiguous-ness of the array is jeopardized.
      // Because we have IMMEDIATELY made a pointer to the original value,the first value in the array, we have preserved the contiguous-ness of the array.
      fmt.Println("array length: ", len(arr))
      
      var arrayLength C.int
      arrayLength = C.int(len(arr))
      // arrayLength = C.int(2)
      
      fmt.Println("array length we are using: ", arrayLength)
      
      arrayMean := C.pop_mean(arrayLength, firstValue)
      fmt.Println("pop_mean (10, 20, 30): ", arrayMean)
      

      这会产生以下结果:

      array length:  3
      array length we are using:  3
      pop_mean (10, 20, 30):  20
      

      或者,如果我们取消注释将 arrayLength 更改为 2 的行,我们会得到以下结果:

      array length:  3
      array length we are using:  2
      pop_mean (10, 20, 30):  15
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-09
        • 1970-01-01
        • 2016-09-06
        • 2012-07-23
        相关资源
        最近更新 更多