dongran1779
2014-08-15 13:31
浏览 393
已采纳

cgo-如何将字符串转换为C固定的char数组

I'm trying to instantiate a C struct inside my Go code. The struct is defined like this, (in an external library that I cannot modify):

typedef struct {
    char field1[256];
} S1

In go, I did this:

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...
}

But it doesn't compile because:

cannot use cStr (type *C.char) as type [256]C.char in field value

I've tried forcing ([256]C.char)(cStr) but it obviously doesn't work either.

Is there a way to achieve what I'm trying to do?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

相关推荐 更多相似问题