英文:
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.double
和float64
是相同的底层类型,我们可以将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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论