【发布时间】:2022-02-08 18:02:44
【问题描述】:
我可以从 C per below 调用不带参数的 Go 函数。这通过go build 编译并打印
Hello from Golang main function!
CFunction says: Hello World from CFunction!
Hello from GoFunction!
main.go
package main
//extern int CFunction();
import "C"
import "fmt"
func main() {
fmt.Println("Hello from Golang main function!")
//Calling a CFunction in order to have C call the GoFunction
C.CFunction();
}
//export GoFunction
func GoFunction() {
fmt.Println("Hello from GoFunction!")
}
file1.c
#include <stdio.h>
#include "_cgo_export.h"
int CFunction() {
char message[] = "Hello World from CFunction!";
printf("CFunction says: %s\n", message);
GoFunction();
return 0;
}
现在,我想将一个字符串/字符数组从 C 传递给 GoFunction。
根据cgo documentation中的“C references to Go”这是可能的,所以我在GoFunction中添加了一个字符串参数并将char数组message传递给GoFunction:
main.go
package main
//extern int CFunction();
import "C"
import "fmt"
func main() {
fmt.Println("Hello from Golang main function!")
//Calling a CFunction in order to have C call the GoFunction
C.CFunction();
}
//export GoFunction
func GoFunction(str string) {
fmt.Println("Hello from GoFunction!")
}
file1.c
#include <stdio.h>
#include "_cgo_export.h"
int CFunction() {
char message[] = "Hello World from CFunction!";
printf("CFunction says: %s\n", message);
GoFunction(message);
return 0;
}
go build 我收到此错误:
./file1.c:7:14: error: passing 'char [28]' to parameter of incompatible type 'GoString'
./main.go:50:33: note: passing argument to parameter 'p0' here
根据上面"C? Go? Cgo!" blog post的“字符串和事物”部分:
Go 和 C 字符串之间的转换是通过 C.CString、C.GoString 和 C.GoStringN 函数完成的。
但是这些是在 Go 中使用的,如果我想将字符串数据传递到 Go 中没有帮助。
【问题讨论】:
-
如果你阅读下面的文档,将会生成一个
_cgo_export.h,类型为GoString,你可以使用它。它看起来像:typedef struct { const char *p; GoInt n; } GoString