如何将[1024] C.char转换为[1024]字节 [英] How to convert [1024]C.char to [1024]byte

查看:175
本文介绍了如何将[1024] C.char转换为[1024]字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  char my_buf [BUF_SIZE]; 

到这个Go(数组)类型:

  type buffer [C.BUF_SIZE] byte 

?试图做一个接口转换给我这个错误:

pre $ $ $ $ c $不能转换(* _Cvar_my_buf)(类型[1024] C.char) to type [1024] byte


解决方案

最简单和最安全的方法是将它复制到一个切片,而不是专门指向 [1024] byte

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

要直接使用内存而无需复制,您可以通过 unsafe.Pointer 来投射它。

< (unsafe.Pointer(& C.my_buf))[:int(C.BUFF_SIZE):int(C)如果BUFF_SIZE是一个常量
myArray:= *(* [C.BUFF_SIZE] byte)(unsafe.Pointer(& C.my_buf))


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

解决方案

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

这篇关于如何将[1024] C.char转换为[1024]字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆