使用C中的字符串参数调用Go函数?

时间:2016-09-26 17:26:23

标签: c go cgo

我可以在没有来自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;
}

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

根据cgo documentation中的“C引用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

其他参考: https://blog.golang.org/c-go-cgo(发布3个链接的声誉不足) 根据上面博客文章的“字符串和事物”部分:“Go和C字符串之间的转换是使用C.CString,C.GoString和C.GoStringN函数完成的。”但是这些用于Go,如果我想将字符串数据传递给Go,则无用。

2 个答案:

答案 0 :(得分:3)

C中的字符串是*C.char,而不是Go string。 导出的函数是否接受正确的C类型,并在Go:

中根据需要进行转换
//export GoFunction
func GoFunction(str *C.char) {
    fmt.Println("Hello from GoFunction!")
    fmt.Println(C.GoString(str))
}

答案 1 :(得分:2)

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

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;
相关问题