2 回答

TA貢獻1757條經驗 獲得超8個贊
將數組名傳遞給函數時,傳遞的是初始元素的位置。在被調用的函數中,這個參數是一個局部變量,所以數組名參數是一個指針,即一個包含地址的變量。
C 程序設計語言,第 2 版
切片類型
切片是底層數組的連續段的描述符,并提供對該數組中元素編號序列的訪問。
與數組一樣,切片是可索引的并且具有長度。可以通過內置函數 len 發現切片 s 的長度;與數組不同,它可能會在執行期間發生變化。這些元素可以通過整數索引 0 到 len(s)-1 尋址。給定元素的切片索引可能小于基礎數組中同一元素的索引。
切片一旦被初始化,總是與保存其元素的底層數組相關聯。
Go 編程語言規范
參考:Go 命令 cgo
對于切片a
,C 函數的參數pop_mean(int numPoints, double a[])
是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

TA貢獻1827條經驗 獲得超9個贊
我發現您必須發送指向數組中第一個值的指針,而不是發送指向切片第一個元素或切片本身的指針。
而且我還遇到了一個問題,我創建了一個新變量,該變量被分配了切片中第一項的值,后來創建了一個指向該變量的指針(不再是原始數組的一部分),而不是創建指向數組中第一項的指針(就像我想要的那樣)。
下面是工作代碼,帶有注釋以幫助避免上面段落中的問題。
// 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
- 2 回答
- 0 關注
- 153 瀏覽
添加回答
舉報