将一个CGO数组转换为切片。

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

casting a cgo array into a slice

问题

目前,我将CGO双精度数组转换为float64切片的方法如下:

doubleSlc := [6]C.double{}

// 填充doubleSlc

floatSlc := []float64{float64(doubleSlc[0]), float64(doubleSlc[1]), float64(doubleSlc[2]),
                      float64(doubleSlc[3]), float64(doubleSlc[4]), float64(doubleSlc[5])}

是否有更简洁的方法来完成相同的操作?我认为这也可以看作是在Go中在不同类型的切片/数组之间进行转换的一般方法。

英文:

At the moment I do this for casting a CGO array of doubles into a slice of float64:

doubleSlc := [6]C.double{}

// Fill doubleSlc

floatSlc := []float64{float64(doubleSlc[0]), float64(doubleSlc[1]), float64(doubleSlc[2]),
                      float64(doubleSlc[3]), float64(doubleSlc[4]), float64(doubleSlc[5])}

Is there a less cumbersome way of doing the same thing? I suppose this can also be seen as a general way of casting between slices/arrays of different types in Go.

答案1

得分: 2

你可以通过以下两种方式来完成这个任务,一种是正常和安全的方式:

c := [6]C.double{1, 2, 3, 4, 5, 6}
fs := make([]float64, len(c))
for i := range c {
    fs[i] = float64(c[i])
}

或者你可以采用不可移植的方式来作弊:

c := [6]C.double{1, 2, 3, 4, 5, 6}
cfa := (*[6]float64)(unsafe.Pointer(&c))
cfs := cfa[:]

如果C.doublefloat64是相同的底层类型,我们可以将C.double数组的指针转换为相同大小的float64数组的指针,然后对该数组进行切片。

当然,这个方法被称为unsafe是有很好的原因的。

英文:

You have the normal and safe way of doing this:

c := [6]C.double{ 1, 2, 3, 4, 5, 6 }
fs := make([]float64, len(c))
for i := range c {
        fs[i] = float64(c[i])
}

Or you could cheat unportably and do this:

c := [6]C.double{ 1, 2, 3, 4, 5, 6 }
cfa := (*[6]float64)(unsafe.Pointer(&c))
cfs := cfa[:]

If C.double and float64 are the same underlying type we can take a pointer to the C.double array, unsafely cast it to a pointer to a same size float64 array, then take a slice of that array.

Of course it's called unsafe for a very good reason.

huangapple
  • 本文由 发表于 2016年4月11日 15:28:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/36542385.html
匿名

发表评论

匿名网友

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

确定