gocgo

How to convert [1024]C.char to [1024]byte


How do I convert this C (array) type:

char my_buf[BUF_SIZE];

to this Go (array) type:

type buffer [C.BUF_SIZE]byte

? Trying to do an interface conversion gives me this error:

cannot convert (*_Cvar_my_buf) (type [1024]C.char) to type [1024]byte

Solution

  • The easiest and safest way is to copy it to a slice, not specifically to [1024]byte

    mySlice := C.GoBytes(unsafe.Pointer(&C.my_buff), C.BUFF_SIZE)
    

    To use the memory directly without a copy, you can "cast" it through an unsafe.Pointer.

    mySlice := unsafe.Slice((*byte)(unsafe.Pointer(&C.my_buf)), C.BUFF_SIZE)
    // and if you need an array type, the slice can be converted
    myArray := ([C.BUFF_SIZE]byte)(mySlice)