1.golang generate c-shared type to so
Set up folder Hello, create the Main.go file with the contents as follows
Package Mainimport "C" Func Main () {}//export hellofunc hello () string {return "Hello"}//export Testfunc Test () {println ("E Xport Test ")}
Generate so script file, command line:
Genetic libhello.so libhello.h File
2.c Language Call libhello.so
Copy the libhello.so to the/usr/lib for running
Create a new folder Hello_test, copy the libhello.so libhello.h to the folder Hello_test
Change the libhello.h to gostring type to _gostring
Create a main.c with the following content
#include <stdio.h> #include "libhello.h" void Main () { _gostring str; str = Hello (); Test (); printf ("%d\n", STR.N);}
The compile command is as follows: GCC main.c-o t1-i./-l./-lhello
3.golang Call libhello.so
Create the Main.go file with the following contents:
Package main/* #include <stdio.h> #include "libhello.h" #cgo Linux CFLAGS:-l./-i./#cgo linux ldflags:-l./-i./-lhel Lo*/import "C" Import ("FMT") func main () {str: = C.hello () c.test () fmt. Println (str)}
Generate script file b.sh content as follows
Export goarch= "386" Export gobin= "/home/ender/download/go/bin" Export goexe= "" Export gohostarch= "386" Export gohostos= "Linux "Export goos=" Linux "Export gopath="/home/ender/go:/home/ender/download/goproject "Export gorace=" "Export goroot="/home/ ender/download/go "Export gotooldir="/home/ender/download/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 requires sudo chmod 777 b.sh after execution
./test
./t1
Run
Golang generates c-shared so for the C language or Golang call to an example