【发布时间】:2021-11-15 19:18:44
【问题描述】:
如何将 golang 字符串添加到我在 cgo 中创建的 c 结构中。代码如下:
package main
/*
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
typedef struct Point {
int x, y;
} Point;
typedef struct Resp {
char response;
} Resp;
*/
import "C"
import (
"fmt"
"io/ioutil"
"unsafe"
)
type CPoint struct {
Point C.Point
Resp C.Resp
}
func main() {
var r string = "Hello World"
resp := unsafe.Pointer(C.char(r))
point := CPoint{
Point: C.Point{x: 1, y: 2},
Resp: C.Resp{response: resp},
}
fmt.Println(point)
}
但是每当我运行它时,我都会收到此错误
cannot convert r (type string) to type _Ctype_char
我该如何解决?如何将 r 转换为类型 _Ctype_char?
另外,你将如何获得 c 结构“Resp”中的值?
package main
/*
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
typedef struct Point {
int x, y;
} Point;
typedef struct Resp {
char response; // <-- How can I get this value in my go code?
} Resp;
*/
【问题讨论】:
-
不能用
r := "hello world"吗? -
同样的事情,仍然报同样的错误。