我希望在我的Go代码中实例化一个C结构体。这个结构体是这样定义的(在一个我不能修改的外部库中):
typedef struct {
char field1[256];
} S1
在Go中,我这样做:
func myfunc(mystr string){
// We need to convert mystr from string to char array
cStr := C.CString(mystr)
defer C.free(unsafe.Pointer(cStr)
// Should work now
s1 := &C.S1{field1: cStr}
// Do something with s1...
}
但是它无法编译,因为:
在字段值中不能使用cStr (类型*C.char)作为类型[256]C.char。
我尝试强制使用([256]C.char)(cStr),但显然也不起作用。
有没有办法实现我想做的事情?
copy(sq.fields[:], mystr)
的方法。 - fuz