我可以从 C 调用一个没有参数的 Go 函数,按照下面的 https://github.com/joeprivacy/crefgo_hello_world。这通过编译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。
根据《C 对 Go 的引用》CGO文档 https://golang.org/cmd/cgo/这是可能的,所以我向 GoFunction 添加一个字符串参数并传递 char 数组message
转到函数:
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;
}
Upon 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?走?Cgo!”博客文章 https://blog.golang.org/c-go-cgo:
Go 和 C 字符串之间的转换是通过 C.CString、C.GoString 和 C.GoStringN 函数完成的。
但这些是在 Go 中使用的,如果我想将字符串数据传递到 Go 中,这些并没有帮助。