C字符名称[8]到GoLang名称[8]字节 [英] C char name[8] to GoLang Name [8]byte
本文介绍了C字符名称[8]到GoLang名称[8]字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个C函数可以填充C结构:
I've got a C function that fills a C struct:
typedef struct {
char name[8];
}
我需要将数据复制到具有相同内容的Go lang结构中:
I need to copy data into Go lang struct that has the same content:
type sData struct {
Name [8]byte
}
该结构具有多个尺寸的参数:4、12、32,因此最好具有一个功能不只一个尺寸的函数.
The structure has parameters of multiple sizes: 4, 12, 32 so it would be nice to have a function that deals with more than just one size.
谢谢
推荐答案
要使其通用一些,可以将C char数组分解为 * C.char
,然后使用 unsafe.Pointer
将其投射回数组.
To make this a little more generic, you can decompose the C char array to a *C.char
, then use unsafe.Pointer
to cast it back to an array.
func charToBytes(dest []byte, src *C.char) {
n := len(dest)
copy(dest, (*(*[1024]byte)(unsafe.Pointer(src)))[:n:n])
}
也许更简单
func charToBytes(src *C.char, sz int) []byte {
dest := make([]byte, sz)
copy(dest, (*(*[1024]byte)(unsafe.Pointer(src)))[:sz:sz])
return dest
}
这篇关于C字符名称[8]到GoLang名称[8]字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文