How to convert [1024]C.char to [1024]byte

杀马特。学长 韩版系。学妹 提交于 2019-11-29 14:21:08

The easiest and safest way is to copy it to a slice, not specifically to [1024]byte

mySlice := C.GoBytes(unsafe.Pointer(&C.my_buff), C.BUFF_SIZE)

To use the memory directly without a copy, you can "cast" it through an unsafe.Pointer.

mySlice := (*[1 << 30]byte)(unsafe.Pointer(&C.my_buf))[:int(C.BUFF_SIZE):int(C.BUFF_SIZE)]
// or for an array if BUFF_SIZE is a constant
myArray := *(*[C.BUFF_SIZE]byte)(unsafe.Pointer(&C.my_buf))

To create a Go slice with the contents of C.my_buf:

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

To create a Go array...

var arr [C.BUF_SIZE]byte
copy(arr[:], C.GoBytes(unsafe.Pointer(&C.my_buf), C.BUF_SIZE))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!