casting a cgo array into a slice

人走茶凉 提交于 2020-01-11 13:11:18

问题


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:


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.



来源:https://stackoverflow.com/questions/36542385/casting-a-cgo-array-into-a-slice

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!