swig開源項目(http://www.swig.org)爲多種編程語言提供了相互訪問的接口生成工具,這裏面也包含了爲go語言生成調用C、C++代碼的功能。Go語言自帶的cgo工具已經支持對C代碼的調用,但對C++代碼的支持確實不行,因此Go1已經把swig的C++這部分功能做爲附帶功能加入(參見Go源代碼\go\misc\swig)。這樣,C++這塊的資源也能夠被Go語言使用了。html
一、爲Go語言生成調用C語言的接口:linux
根據swig的相關文檔指導( http://www.swig.org/Doc2.0/Go.html#Go ),用swig自帶的例子作測試。如下的例子都是在ubuntu12.04下測試完成的。例子來源\swigwin-2.0.7\Examples\go\simplec++
swig -go example.i
gcc -c -fpic example.c
gcc -c -fpic example_wrap.c
gcc -shared example.o example_wrap.o -o example.so
go tool 8g example.go
golang
go tool 8c example_gc.c
這裏會報錯,編程
After reading golang-nuts thread:
原來是沒有設置3個環境變量: GOROOT、 GOARCH和 GOOS。這裏臨時在控制檯設置:ubuntu
export GOROOT=/usr/lib/go
export GOARCH=386
編程語言
export GOOS=linux
工具
go tool 8c -I ${GOROOT}/pkg/${GOOS}_${GOARCH} example_gc.c性能
go tool pack grc example.a example.8 example_gc.8測試
go tool 8g runme.go
go tool 8l -o runme runme.8
//爲了運行runme,還須要export LD_LIBRARY_PATH
export LD_LIBRARY_PATH=${pwd}:${LD_LIBRARY_PATH}
./runme
這樣應該能看到運行結果了
二、爲go語言生成調用C++語言的接口:
例子來源\swigwin-2.0.7\Examples\go\class
swig -c++ -go example.ig++ -g -c -fpic example.cxx example_wrap.cxx
g++ -shared example.o example_wrap.o -o example.so
go tool 8g example.go
export GOROOT=/usr/lib/go
export GOARCH=386
export GOOS=linux
go tool 8c -I ${GOROOT}/pkg/${GOOS}_${GOARCH} example_gc.c
go tool pack grc example.a example.8 example_gc.8
go tool 8g runme.go
go tool 8l -o runme runme.8
//爲了運行runme,還須要export LD_LIBRARY_PATH
export LD_LIBRARY_PATH=${pwd}:${LD_LIBRARY_PATH}
./runme 最後,潑點冷水。調用C或者C++本地代碼,確實能知足性能要求比較高的需求。但要記住,它是一把雙刃劍。它會讓你的解決方案更加複雜,須要花費更多的時間和精力去開發和維護。要不要使用它,只能靠你本身去衡量。