2016-09-26 112 views
2

我可以在不使用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

回答

3

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的名字種類 –

2

,您可以在使用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,但它不會顯示在櫃檯上,因爲我是低代表。 –