一尘不染

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

go

我可以在下面从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!")
}

文件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;
}

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

根据cgo文档中的
“对Go的C引用”,这是可能的,因此我向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!")
}

文件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;
}

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中,则无济于事。


阅读 439

收藏
2020-07-02

共1个答案

一尘不染

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))
}
2020-07-02