1 回答
TA贡献1810条经验 获得超5个赞
您的代码需要 2 个修复:
C 仅表示单个字符/字节 - 不表示字符串。C 字符串为 。
char
char*
您应该使用 从 Go 分配 C 字符串,并释放它。参见:https://pkg.go.dev/cmd/cgo#hdr-Go_references_to_C。
C.CString
C.free
以下是您使用这些修复程序的示例:
package main
// FIX: "char response" replaced with "char *response" below.
/*
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
typedef struct Point {
int x, y;
} Point;
typedef struct Resp {
char *response;
} Resp;
void fill(const char *name, Resp *r) {
printf("name: %s\n", name);
printf("Original value: %s\n", r->response);
r->response = "testing";
}
*/
import "C"
import (
"fmt"
"unsafe"
)
// NOTE: You cannot pass this struct to C.
// Types passed to C must be defined in C (eg, like "Point" above).
type CPoint struct {
Point C.Point
Resp C.Resp
}
func main() {
// FIX: Use CString to allocate a *C.char string.
resp := C.CString("Hello World")
point := CPoint{
Point: C.Point{x: 1, y: 2},
Resp: C.Resp{response: resp},
}
fmt.Println(point)
// Example of calling a C function and converting a C *char string to a Go string:
cname := C.CString("foo")
defer C.free(unsafe.Pointer(cname))
r := &C.Resp{
response: resp, // Use allocated C string.
}
C.fill(cname, r)
goResp := C.GoString(r.response)
fmt.Println(goResp)
// FIX: Release manually allocated string with free(3) when no longer needed.
C.free(unsafe.Pointer(resp))
}
- 1 回答
- 0 关注
- 76 浏览
添加回答
举报