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

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条回答 默认 最新

  • dongsimu4422 2014-08-15 13:44
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!