加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Golang使用swig包装C/C++程序为Go包 For Windows

发布时间:2020-12-16 18:35:33 所属栏目:大数据 来源:网络整理
导读:swig不能直接使用官方的程序,而必须打一个patch 后才能使用。svn下载swig源代码后(看版本号应该是2.0.5了),打上 swig_go_windows2.patch 这个patch。至于怎么打patch,请自行Google之。 swig的编译也是比较折腾的。因为他依赖 yodl2man yodl2html这东西

swig不能直接使用官方的程序,而必须打一个patch 后才能使用。svn下载swig源代码后(看版本号应该是2.0.5了),打上
swig_go_windows2.patch
这个patch。至于怎么打patch,请自行Google之。

swig的编译也是比较折腾的。因为他依赖 yodl2man yodl2html这东西,而这东西又依赖 icmake,不过后来发现这东西不要也行,虽然 swig在 make install的时候没有完全结束,但是生成的东西,已经够用了。

把C写的库包装为 GO包。

首先需要准备两个文件 test.i test.c

$cattest.c#includedoubleMyVar=3.0;intFact(intn){if(n<=1)return1;elsereturnn*Fact(n-1);
}intMyMod(intx,inty){return(x%y);
}char*GetTime(){
time_tltime;
time(&ltime);returnctime(&ltime);
}

$cattest.i
%moduletest
%{externdoubleMyVar;externintFact(intn);externintMyMod(intx,inty);externchar*GetTime();
%}externdoubleMyVar;externintFact(intn);externintMyMod(intx,inty);externchar*GetTime();

需要注意的是 C中的如果要想在Go中可以调用 ,首字母必须要 大写。开始 swig

//初始$ls
test.itest.c//使用swig生成需要的文件$swig-go-windowstest.i
$ls
test.ctest.gotest.itest_dllmain.cxxtest_gc.ctest_wrap.c//分别编译test.ctest_wrap.ctest_dllmain.cxx为目标文件*.o$gcc-ctest.ctest_wrap.ctest_dllmain.cxx//将上一步编译的结果链接成一个动态链接库$gcc-sharedtest.otest_wrap.otest_dllmain.o-otest.dll//编译test.go$8gtest.go//编译test_gc.c$8c-I"go的pkg目录"test_gc.c//将test.8test_gc.8打包成go库,就是一个静态库,相当于gcc里面使用ar命令打包一样。$gopackgrctest.atest.8test_gc.8

至此万事俱备了。写个go 程序来试试。

$catmain.go
packagemain

import"./test"import"fmt"funcmain(){
println(test.Fact(5))//println(test.MyVar)//不能直接调用必须使用gettersetter来调用如下
test.SetMyVar(99)//来设置MyVar的值
fmt.Printf("%f
",test.GetMyVar())//取得刚设置的值。
println(test.MyMod(10,3))
println(test.GetTime())
}

$8gmain.go
$8lmain.8$./8.out.exe1201ThuJun2304:06:402011

现在把 test.dll改名,看看这个程序是不是真调用 了这个动态链接库。

如果要在其它地方使用只需要 test.a 及 test.dll 两个文件 。。test.a就是go的库,这是魔法所在,就是这样东西负责调用 C里面的函数。。因为Go是静态编译,所以编译好的Go程序就不需要 test.a这东西了,只要test.dll带上就行了。。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读