I've managed to get the following function working in Go. But I want to optimize/generalize the code such that this function would return me a pointer to the first byte of any value I pass into the function. Currently it will only work for []uint32, but I want to use it to get the starting memory address as a *byte for many other types (i.e. byte[], int[], string, etc).
Is there a more generic way to do this rather than catching every single type I need to address as case statements?
Go Playground Link for below code: http://ift.tt/2f5Br0G
package main
import (
"fmt"
"reflect"
"unsafe"
)
func ToBytePointer(data interface{}) *byte {
fmt.Println("Received type is", reflect.TypeOf(data))
switch data.(type) {
case []uint32:
typedData := data.([]uint32)
return (*byte)(unsafe.Pointer(&typedData[0]))
default:
return nil
}
}
func main() {
var data = []uint32{1, 2, 3}
var dataBytePointer = (*byte)(unsafe.Pointer(&data[0]))
fmt.Println(dataBytePointer, ToBytePointer(data))
}
Aucun commentaire:
Enregistrer un commentaire