cgo - How to convert string to C fixed char array

。_饼干妹妹 提交于 2019-12-04 09:17:20

The simplest solution is to change your struct's field definition to a char-pointer which is pretty standard for strings in C:

typedef struct {
    char *field1;
} S1

The more complex solution would be [1]:

arr := [256]C.char{}

for i := 0; i < len(mystr) && i < 255; i++ { // leave element 256 at zero
    arr[i] = C.char(mystr[i])
}

s1 := &C.S1{field1: arr}

[1] Code untested, cannot compile on this workstation.

Unfortunately there aren't any convenience methods for handling [size]C.char as a string in Go (I think I saw a proposal to add this at one point though...)

In my code instead of handling it directly, I opted to manually write the string into the struct when needed with some like

func strCopy(dest *[maxTextExtent]C.char, src []byte) {
    for i, c := range src {
        dest[i] = C.char(c)
    }
    // This is C, we need to terminate the string!
    dest[len(src)] = 0
}

And the way I used to handle it, which is much less safe is

s1 := &C.S1{
    field1: *(*[256]C.char)(unsafe.Pointer(cStr)),
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!