C char name[8] to GoLang Name [8]byte

无人久伴 提交于 2019-12-11 13:29:59

问题


I've got a C function that fills a C struct:

typedef struct {
  char name[8];
}

I need to copy data into Go lang struct that has the same content:

type sData struct {
  Name [8]byte
}

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.

thanks


回答1:


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

Or maybe a little easier

func charToBytes(src *C.char, sz int) []byte {
    dest := make([]byte, sz)
    copy(dest, (*(*[1024]byte)(unsafe.Pointer(src)))[:sz:sz])
    return dest
}


来源:https://stackoverflow.com/questions/37446623/c-char-name8-to-golang-name-8byte

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!