golang 과 C 는 서로 예제 를 호출 합 니 다.

1603 단어 기타
다음 예제 에서 사용 하 는 운영 체 제 는 모두 Liux 이 고 windows 는 비교적 번거롭다.
1.c 언어 호출 golang 라 이브 러 리
1.main.go
package main
 
import "C"
 
func main() {}
 
//export Hello
func Hello() string {
    return "Hello"
}
 
//export Test
func Test() {
    println("export Test")
}

동적 라 이브 러 리 생 성 명령
go build  -buildmode=c-shared -o libhello.so   main.go

a 정적 라 이브 러 리 생 성
#  libhello.a
 go build -buildmode=c-archive -o libhello.a main.go

go 컴 파일 러 는 libhello.h 파일 을 자동 으로 생 성 합 니 다. 
2.main.c
#include 
#include "libhello.h"
 
void main()
{
    GoString str;
    str = Hello();   
    Test();
    printf("%d
",str.n); }

컴 파일 명령
 gcc main.c -o t1 -I./ -L./ -lhello -lpthread

#                 $LD_LIBRARY_PATH      
export LD_LIBRARY_PATH=./:$LD_LIBRARY_PATH

#    
./t1 

2.golang 호출 c 라 이브 러 리
1.toto.h
int x(int);

2.toto.c
int x( int y ) { return y+1; }

 컴 파일 명령
#     .a    
gcc -O2 -c toto.c
ar q libgb.a toto.o


#     .so   
gcc -shared -o libgb.so toto.c

3.test.go
package main

import "fmt"

// #cgo CFLAGS: -I.
// #cgo LDFLAGS: -L. -lgb 
// #include 
import "C"

func main() {
  fmt.Printf("Invoking c library...
") fmt.Println("Done ", C.x(10) ) }

명령:
go build test.go

./test  #    

좋은 웹페이지 즐겨찾기