Search code examples
cgoelfcgo

How to convert Go's []byte to C's *uint8_t


I want to set a uint8_t* in a C struct using Go. The data in Go comes from and ELF and is a byte slice. This is the error I currently get:

cannot use &buf[0] (type *byte) as type *_Ctype_uchar in assignment

using this code:

args.vm_snapshot_data = &buf[0]

How do I do it?

When I use the proper cast:
args.vm_snapshot_data = (*C.uint8_t)(&buf[0])
I get this error:
panic: runtime error: cgo argument has Go pointer to Go pointer


Solution

  • Golang count types rather than compatibility of them. And there's only one method to cast over the place it's using unsafe.Pointer as original value.

    args.vm_snapshot_data = (*C.uint8_t)(unsafe.Pointer(&buf[0]))
    

    If you’re not sure if buf slice will be alive on the Go side (garbage collector might dispose it) at the time when C side using it, then you have to use copy and dispose it manually.

    args.vm_snapshot_data = (*C.uint8_t)(C.CBytes(buf))
    
    ...
    
    C.free(unsafe.Pointer(args.vm_snapshot_data))