当前位置:   article > 正文

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

go build c-shared .so

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

#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

#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

来源:oschina

链接:https://my.oschina.net/u/4326431/blog/4473509

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/秋刀鱼在做梦/article/detail/766941
推荐阅读
相关标签
  

闽ICP备14008679号