Call Go function with string parameter from C?

心不动则不痛 提交于 2019-12-12 19:00:55

问题


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\n", 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\n", 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.


回答1:


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))
}



回答2:


If you want to pass a C string to a function that accepts only Go strings, you can use GoString type on the C side:

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;


来源:https://stackoverflow.com/questions/39708874/call-go-function-with-string-parameter-from-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!