赞
踩
建立文件夹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文件
把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
创建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
运行。
文章来源:https://www.cnblogs.com/coolyylu/p/7008074.html
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。