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

運行


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM