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

huangapple go评论77阅读模式
英文:

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(&amp;C.my_buff), C.BUFF_SIZE)

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

mySlice := (*[1 &lt;&lt; 30]byte)(unsafe.Pointer(&amp;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(&amp;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(&amp;C.my_buf), C.BUF_SIZE)

To create a Go array...

var arr [C.BUF_SIZE]byte
copy(arr[:], C.GoBytes(unsafe.Pointer(&amp;C.my_buf), C.BUF_SIZE))

huangapple
  • 本文由 发表于 2014年12月18日 02:40:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/27532523.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定