golang与C互相调用示例

以下示例使用的操作系统都是linux,windows比较麻烦。

一、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 <stdio.h>
#include "libhello.h"
 
void main()
{
    GoString str;
    str = Hello();   
    Test();
    printf("%d\n",str.n);
}

编译命令

 gcc main.c -o t1 -I./ -L./ -lhello -lpthread

#如果用动态库链接需要将当前路径加到$LD_LIBRARY_PATH中再运行程序
export LD_LIBRARY_PATH=./:$LD_LIBRARY_PATH

#运行程序
./t1 

二、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 <toto.h>
import "C"

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

命令:

go build test.go

./test  #运行测试

猜你喜欢

转载自blog.csdn.net/v6543210/article/details/89436916