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

问题描述:

我可以在不使用C,per below的参数的情况下调用Go功能。这通过go build并打印用C中的字符串参数调用Go函数?

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

现在,我想传递一个字符串/字符数组编译从C到GoFunction。

据“C引用转到”在cgo documentation这是可能的,所以我添加一个字符串参数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!") 
} 

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,这些都没有帮助。

+0

如果您阅读下面的文档,将会有一个'_cgo_export.h'生成'GoString'类型,您可以使用它。它看起来像:'typedef struct {const char * p; GoInt n; } GoString' – JimB

C中的字符串是*C.char,而不是Go string。 让你的导出函数接受正确的C类型,并根据需要将其转换围棋:如果你想C字符串传递给函数只接受去串

//export GoFunction 
func GoFunction(str *C.char) { 
    fmt.Println("Hello from GoFunction!") 
    fmt.Println(C.GoString(str)) 
} 
+0

我想OP在问,怎么能调用一个只接受Go字符串的Go函数。但我想创建一个包装函数是一种方法。 –

+0

@Ainar-G:好点,我本该等待评论回复;) – JimB

+0

这个工程! 当我在排除故障时尝试了这个,我错误地使用了'str * C.Char',导致错误 '无法确定C.Char的名字种类 –

,您可以在使用GoString型C端:

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; 
+1

非常感谢!我upvoted,但它不会显示在柜台上,因为我是低代表。 –