英文:
How to convert [1024]C.char to [1024]byte
问题
如何将这个 C(数组)类型转换为 Go(数组)类型:
char my_buf[BUF_SIZE];
转换为:
type buffer [C.BUF_SIZE]byte
?尝试进行接口转换时,我得到以下错误:
cannot convert (*_Cvar_my_buf) (type [1024]C.char) to type [1024]byte
英文:
How do I convert this C (array) type:
char my_buf[BUF_SIZE];
to this Go (array) type:
type buffer [C.BUF_SIZE]byte
? Trying to do an interface conversion gives me this error:
cannot convert (*_Cvar_my_buf) (type [1024]C.char) to type [1024]byte
答案1
得分: 9
最简单和最安全的方法是将其复制到一个切片中,而不是特定的[1024]byte
。
mySlice := C.GoBytes(unsafe.Pointer(&C.my_buff), C.BUFF_SIZE)
要直接使用内存而不进行复制,可以通过unsafe.Pointer
进行“类型转换”。
mySlice := (*[1 << 30]byte)(unsafe.Pointer(&C.my_buf))[:int(C.BUFF_SIZE):int(C.BUFF_SIZE)]
// 或者对于一个数组,如果BUFF_SIZE是一个常量
myArray := *(*[C.BUFF_SIZE]byte)(unsafe.Pointer(&C.my_buf))
英文:
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))
答案2
得分: 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))
英文:
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))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论