如何转换这个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
型
b5lpy0ml1#
最简单、最安全的方法是将其复制到切片,而不是专门复制到[1024]byte
[1024]byte
mySlice := C.GoBytes(unsafe.Pointer(&C.my_buff), C.BUFF_SIZE)
字符串要直接使用内存而不使用副本,您可以通过unsafe.Pointer对其进行“强制转换”。
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)
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))
2条答案
按热度按时间b5lpy0ml1#
最简单、最安全的方法是将其复制到切片,而不是专门复制到
[1024]byte
字符串
要直接使用内存而不使用副本,您可以通过
unsafe.Pointer
对其进行“强制转换”。型
dw1jzc5e2#
使用C.my_buf的内容创建Go切片:
字符串
创建围棋数组...
型