问题描述
我试图在Go代码中实例化一个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:
我试过强制([256] C.char)(cStr),但它显然不起作用。
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?
推荐答案
最简单的解决方案是将你的结构的字段定义改成一个字符指针,这对于C中的字符串来说是非常标准的:
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 :
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}
未经测试的代码,无法在此工作站上编译。
Code untested, cannot compile on this workstation.
这篇关于cgo - 如何将字符串转换为C固定字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!