本文介绍了将cgo数组转换为切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我这样做是为了将CGO的double数组转换为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])}

做同样的事情有没有那么麻烦的方法?我想这也可以看作是Go中不同类型的切片/数组之间进行转换的一种通用方法.

解决方案

您拥有正常且安全的方法:

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数组的指针,然后采用该数组的一个切片. /p>

当然,有很好的理由将其称为unsafe.

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.

解决方案

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.

这篇关于将cgo数组转换为切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 05:42