首页 > 代码库 > golang生成c-shared so供c语言或者golang调用到例子

golang生成c-shared so供c语言或者golang调用到例子

1.golang生成c-shared类型到so

建立文件夹hello,创建main.go文件,内容如下

package main

import "C"

func main() {}

//export Hello
func Hello() string {
	return "Hello"
}

//export Test
func Test() {
	println("export Test")
}

 生成so脚本文件,命令行:

export GOARCH="386"
export GOBIN="/home/ender/下载/go/bin"
export GOEXE=""
export GOHOSTARCH="386"
export GOHOSTOS="linux"
export GOOS="linux"
export GOPATH="/home/ender/go:/home/ender/下载/goproject"
export GORACE=""
export GOROOT="/home/ender/下载/go"
export GOTOOLDIR="/home/ender/下载/go/pkg/tool/linux_386"
export GCCGO="gccgo"
export GO386=""
export CC="gcc"
export GOGCCFLAGS="-fPIC -m32 -pthread -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build128906296=/tmp/go-build -gno-record-gcc-switches"
export CXX="g++"
export CGO_ENABLED="1"
export PKG_CONFIG="pkg-config"
export CGO_CFLAGS="-g -O2"
export CGO_CPPFLAGS=""
export CGO_CXXFLAGS="-g -O2"
export CGO_FFLAGS="-g -O2"
export CGO_LDFLAGS="-g -O2"

$GOBIN/go build -x -v -ldflags "-s -w" -buildmode=c-shared -o libhello.so   main.go 

成生libhello.so  libhello.h文件

 

2.c语言调用libhello.so

  把libhello.so拷贝到/usr/lib中用于运行

  新建一个文件夹hello_test ,把libhello.so  libhello.h拷贝到文件夹hello_test中

  把libhello.h中到GoString类型更改为_GoString

  创建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

 

3.golang调用libhello.so

创建main.go文件内容如下:

package main

/*
#include <stdio.h>
#include "libhello.h"
#cgo linux CFLAGS: -L./ -I./
#cgo linux LDFLAGS: -L./ -I./ -lhello
*/
import "C"

import (
	"fmt"
)

func main() {

	str := C.Hello()
	C.Test()
	fmt.Println(str)
}

 生成脚本文件b.sh内容如下

export GOARCH="386"
export GOBIN="/home/ender/下载/go/bin"
export GOEXE=""
export GOHOSTARCH="386"
export GOHOSTOS="linux"
export GOOS="linux"
export GOPATH="/home/ender/go:/home/ender/下载/goproject"
export GORACE=""
export GOROOT="/home/ender/下载/go"
export GOTOOLDIR="/home/ender/下载/go/pkg/tool/linux_386"
export GCCGO="gccgo"
export GO386=""
export CC="gcc"
export GOGCCFLAGS="-fPIC -m32 -pthread -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build128906296=/tmp/go-build -gno-record-gcc-switches"
export CXX="g++"
export CGO_ENABLED="1"
export PKG_CONFIG="pkg-config"
export CGO_CFLAGS="-g -O2"
export CGO_CPPFLAGS=""
export CGO_CXXFLAGS="-g -O2"
export CGO_FFLAGS="-g -O2"
export CGO_LDFLAGS="-g -O2"

$GOBIN/go build  -o ./test main.go

 

 

 

b.sh需要sudo chmod  777 b.sh后执行

./test

./t1

运行

golang生成c-shared so供c语言或者golang调用到例子