2016-09-26 1 views
2

C에서 매개 변수없이 Go 함수를 호출 할 수 있습니다 (per below). 이 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으로

이 가능하다 cgo documentation에서 '이동 C 참조 "에 따르면

, 그래서 GoFunction에 문자열 매개 변수를 추가하고 GoFunction에 문자 배열 message 합격 :

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

./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 build시나는이 오류가 나타납니다 이동 및 C 문자열은 C.CString, C.GoString 및 C.GoStringN 함수를 사용하여 수행됩니다. " 하지만 이것들은 Go에서 사용하기위한 것이며 문자열 데이터를 Go에 전달하려는 경우에는 도움이되지 않습니다.

+0

그 아래의 문서를 읽는다면 사용할 수있는 GoString 형식의'_cgo_export.h '가 생성됩니다. 그것은 다음과 같이 보입니다 :'typedef struct {const char * p; GoInt n; } GoString' – JimB

답변

3

C에서의 문자열은 *C.char이고, 이동은 string이 아닙니다. 당신이에 GoString 유형을 사용할 수 있습니다,

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

을 만 문자열을 이동 받아들이는 함수에 C 문자열을 전달하려는 경우 내 보낸 함수가 올바른 C 타입을 수용했으며, 이동에 필요한 변환 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하지만 나는 낮은 담당자이기 때문에 카운터에 표시되지 않습니다. –

관련 문제