Home >Backend Development >Golang >How to Convert a C [1024]C.char Array to a Go [1024]byte Array?
In Go, when dealing with C data structures, it's often necessary to convert between corresponding Go types. One such conversion is transforming a C array of characters (char[1024]) to a Go array of bytes ([1024]byte).
Directly attempting to convert between these types may result in an error like "cannot convert (*_Cvar_my_buf) (type [1024]C.char) to type [1024]byte". To overcome this, we present two approaches:
The recommended approach is to first convert the C array into a Go slice using C.GoBytes():
mySlice := C.GoBytes(unsafe.Pointer(&C.my_buf), C.BUFF_SIZE)
This returns a Go slice ([]byte) representing the memory pointed to by the C my_buf array.
Alternatively, you can "cast" the C array's pointer through an unsafe.Pointer to create a Go slice:
mySlice := unsafe.Slice((*byte)(unsafe.Pointer(&C.my_buf)), C.BUFF_SIZE)
This approach provides direct access to the memory but should be handled with care.
To obtain the desired [1024]byte array, you can convert the slice:
myArray := ([C.BUFF_SIZE]byte)(mySlice)
The above is the detailed content of How to Convert a C [1024]C.char Array to a Go [1024]byte Array?. For more information, please follow other related articles on the PHP Chinese website!