0

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.

prl900
  • 4,029
  • 4
  • 33
  • 40
  • The main problem here is casting the array into a new type, not the array to slice same type transformation... – prl900 Apr 11 '16 at 10:01
  • Sorry, missed that. there's no way other than a loop, but of course no need to manually do it one by one. – Not_a_Golfer Apr 11 '16 at 10:03

1 Answers1

2

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.

Art
  • 19,807
  • 1
  • 34
  • 60