doujiao1981 2016-09-26 17:26
浏览 247
已采纳

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

I can call a Go function without parameters from C, per below. This compiles via go build and prints

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
", message);
  GoFunction();
  return 0;
}

Now, I want to pass a string/char array from C to GoFunction.

According to "C references to Go" in the cgo documentation this is possible, so I add a string parameter to GoFunction and pass the char array message to 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
", message);
  GoFunction(message);
  return 0;
}

Upon go build I receive this error:

./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

Other references: https://blog.golang.org/c-go-cgo (not enough reputation to post 3 links) According to the "strings and things" section of the above blog post: "Conversion between Go and C strings is done with the C.CString, C.GoString, and C.GoStringN functions." but these are for use in Go, and not helpful if I want to pass string data into Go.

  • 写回答

2条回答 默认 最新

  • doudui1850 2016-09-26 17:33
    关注

    A string in C is a *C.char, not a Go string. Have your exported function accept the correct C type, and convert it as necessary in Go:

    //export GoFunction
    func GoFunction(str *C.char) {
        fmt.Println("Hello from GoFunction!")
        fmt.Println(C.GoString(str))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog