1.golang生成c-shared类型到so
建立文件夹hello,创建main.go文件,内容如下
packagemain import"C" funcmain(){} //exportHello funcHello()string{ return"Hello" } //exportTest funcTest(){ println("exportTest") }生成so脚本文件,命令行:
exportGOARCH="386" exportGOBIN="/home/ender/下载/go/bin" exportGOEXE="" exportGOHOSTARCH="386" exportGOHOSTOS="linux" exportGOOS="linux" exportGOPATH="/home/ender/go:/home/ender/下载/goproject" exportGORACE="" exportGOROOT="/home/ender/下载/go" exportGOTOOLDIR="/home/ender/下载/go/pkg/tool/linux_386" exportGCCGO="gccgo" exportGO386="" exportCC="gcc" exportGOGCCFLAGS="-fPIC-m32-pthread-fmessage-length=0-fdebug-prefix-map=/tmp/go-build128906296=/tmp/go-build-gno-record-gcc-switches" exportCXX="g++" exportCGO_ENABLED="1" exportPKG_CONFIG="pkg-config" exportCGO_CFLAGS="-g-O2" exportCGO_CPPFLAGS="" exportCGO_CXXFLAGS="-g-O2" exportCGO_FFLAGS="-g-O2" exportCGO_LDFLAGS="-g-O2" $GOBIN/gobuild-x-v-ldflags"-s-w"-buildmode=c-shared-olibhello.so main.go成生libhello.solibhello.h文件
2.c语言调用libhello.so
把libhello.so拷贝到/usr/lib中用于运行
新建一个文件夹hello_test,把libhello.solibhello.h拷贝到文件夹hello_test中
把libhello.h中到GoString类型更改为_GoString
创建main.c,内容如下
#include<stdio.h> #include"libhello.h" voidmain() { _GoStringstr; str=Hello(); Test(); printf("%d\n",str.n); }编译命令如下:gccmain.c-ot1-I./-L./-lhello
3.golang调用libhello.so
创建main.go文件内容如下:
packagemain /* #include<stdio.h> #include"libhello.h" #cgolinuxCFLAGS:-L./-I./ #cgolinuxLDFLAGS:-L./-I./-lhello */ import"C" import( "fmt" ) funcmain(){ str:=C.Hello() C.Test() fmt.Println(str) }生成脚本文件b.sh内容如下
exportGOARCH="386" exportGOBIN="/home/ender/下载/go/bin" exportGOEXE="" exportGOHOSTARCH="386" exportGOHOSTOS="linux" exportGOOS="linux" exportGOPATH="/home/ender/go:/home/ender/下载/goproject" exportGORACE="" exportGOROOT="/home/ender/下载/go" exportGOTOOLDIR="/home/ender/下载/go/pkg/tool/linux_386" exportGCCGO="gccgo" exportGO386="" exportCC="gcc" exportGOGCCFLAGS="-fPIC-m32-pthread-fmessage-length=0-fdebug-prefix-map=/tmp/go-build128906296=/tmp/go-build-gno-record-gcc-switches" exportCXX="g++" exportCGO_ENABLED="1" exportPKG_CONFIG="pkg-config" exportCGO_CFLAGS="-g-O2" exportCGO_CPPFLAGS="" exportCGO_CXXFLAGS="-g-O2" exportCGO_FFLAGS="-g-O2" exportCGO_LDFLAGS="-g-O2" $GOBIN/gobuild-o./testmain.gob.sh需要sudochmod777b.sh后执行
./test
./t1
运行
本文内容总结:
原文链接:https://www.cnblogs.com/coolyylu/p/7008074.html