码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-06-14 13:16:23      阅读:478      评论:0      收藏:0      [点我收藏+]

标签:文件内容   ccf   path   port   string   mod   highlight   import   arc   

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

运行

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

标签:文件内容   ccf   path   port   string   mod   highlight   import   arc   

原文地址:http://www.cnblogs.com/coolyylu/p/7008074.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!