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

Joe*_*rks 3 c go cgo

我可以从 C 调用一个没有参数的 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!")
}
Run Code Online (Sandbox Code Playgroud)

文件1.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;
}
Run Code Online (Sandbox Code Playgroud)

现在,我想将一个字符串/字符数组从 C 传递给 GoFunction。

根据cgo 文档中的“C 对 Go 的引用”,这是可能的,所以我向 GoFunction 添加了一个字符串参数并将字符数组传递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!")
}
Run Code Online (Sandbox Code Playgroud)

文件1.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;
}
Run Code Online (Sandbox Code Playgroud)

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

其他参考资料:( https://blog.golang.org/c-go-cgo没有足够的声誉发布 3 个链接)根据上述博客文章的“字符串和事物”部分:“Go 和 C 字符串之间的转换是通过 C.CString、C.GoString 和 C.GoStringN 完成的职能。” 但这些是在 Go 中使用的,如果我想将字符串数据传递到 Go 中,则没有帮助。

Jim*_*imB 5

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

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


Ain*_*r-G 5

如果要将 C 字符串传递给仅接受 Go 字符串的函数,可以GoString在 C 端使用 type:

char message[] = "Hello World from CFunction!";
printf("CFunction says: %s\n", message);
GoString go_str = {p: message, n: sizeof(message)}; // N.B. sizeof(message) will
                                                    // only work for arrays, not
                                                    // pointers.
GoFunction(go_str);
return 0;
Run Code Online (Sandbox Code Playgroud)