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

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?

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值