gpt4 book ai didi

从 C 调用带有字符串参数的 Go 函数?

转载 作者:IT王子 更新时间:2023-10-29 01:26:47 25 4
gpt4 key购买 nike

我可以从 C 调用一个没有参数的 Go 函数,per below .这通过 go build 编译并打印

Hello from Golang main function!
CFunction says: Hello World from CFunction!
Hello from GoFunction!

ma​​in.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 对 Go 的引用”这是可能的,所以我向 GoFunction 添加一个字符串参数并将字符数组 message 传递给 GoFunction:

ma​​in.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 :

Conversion between Go and C strings is done with the C.CString, C.GoString, and C.GoStringN functions.

但是这些是在 Go 中使用的,如果我想将字符串数据传递到 Go 中则没有帮助。

最佳答案

C 中的字符串是 *C.char,而不是 Go string。让你导出的函数接受正确的 C 类型,并根据需要在 Go 中转换它:

//export GoFunction
func GoFunction(str *C.char) {
fmt.Println("Hello from GoFunction!")
fmt.Println(C.GoString(str))
}

关于从 C 调用带有字符串参数的 Go 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39708874/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com