Go语言 如何将[1024]C.char转换为[1024]byte

cbjzeqam  于 9个月前  发布在  Go
关注(0)|答案(2)|浏览(95)

如何转换这个C(数组)类型:

char my_buf[BUF_SIZE];

字符串
Go(array)类型:

type buffer [C.BUF_SIZE]byte


?尝试进行接口转换时出现此错误:

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

b5lpy0ml

b5lpy0ml1#

最简单、最安全的方法是将其复制到切片,而不是专门复制到[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)

dw1jzc5e

dw1jzc5e2#

使用C.my_buf的内容创建Go切片:

arr := C.GoBytes(unsafe.Pointer(&C.my_buf), C.BUF_SIZE)

字符串
创建围棋数组...

var arr [C.BUF_SIZE]byte
copy(arr[:], C.GoBytes(unsafe.Pointer(&C.my_buf), C.BUF_SIZE))

相关问题