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

问题描述 投票:0回答:2

如何转换这个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
go cgo
2个回答
11
投票

最简单、最安全的方法就是复制到切片,而不是专门复制到

[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)

2
投票

使用 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))
© www.soinside.com 2019 - 2024. All rights reserved.