如何转换这个C(数组)类型:
char my_buf[BUF_SIZE];
对于这个 Go(数组)类型:
type buffer [C.BUF_SIZE]byte
?尝试进行接口转换时出现此错误:
cannot convert (*_Cvar_my_buf) (type [1024]C.char) to type [1024]byte
最简单、最安全的方法就是复制到切片,而不是专门复制到
[1024]byte
mySlice := C.GoBytes(unsafe.Pointer(&C.my_buff), C.BUFF_SIZE)
要直接使用内存而不需要副本,您可以通过
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)
使用 C.my_buf 的内容创建 Go 切片:
arr := C.GoBytes(unsafe.Pointer(&C.my_buf), C.BUF_SIZE)
创建 Go 数组...
var arr [C.BUF_SIZE]byte
copy(arr[:], C.GoBytes(unsafe.Pointer(&C.my_buf), C.BUF_SIZE))