I've got a C function that fills a C struct:
typedef struct {
char name[8];
}
I need to copy data into Go lang struct that has the same content:
type sData struct {
Name [8]byte
}
The structure has parameters of multiple sizes: 4, 12, 32 so it would be nice to have a function that deals with more than just one size.
thanks
To make this a little more generic, you can decompose the C char array to a *C.char
, then use unsafe.Pointer
to cast it back to an array.
func charToBytes(dest []byte, src *C.char) {
n := len(dest)
copy(dest, (*(*[1024]byte)(unsafe.Pointer(src)))[:n:n])
}
Or maybe a little easier
func charToBytes(src *C.char, sz int) []byte {
dest := make([]byte, sz)
copy(dest, (*(*[1024]byte)(unsafe.Pointer(src)))[:sz:sz])
return dest
}