Golang使用CGO與Plugin技術(shù)運(yùn)行加載C動(dòng)態(tài)庫(kù)
文章簡(jiǎn)介
本文介紹一種 Golang 程序在運(yùn)行時(shí)加載 C 動(dòng)態(tài)庫(kù)的技術(shù),跳過(guò)了 Golang 項(xiàng)目編譯階段需要鏈接 C 動(dòng)態(tài)庫(kù)的過(guò)程,提高了 Golang 項(xiàng)目開(kāi)發(fā)部署的靈活性。
技術(shù)背景
Golang 程序調(diào)用 OpenCC 動(dòng)態(tài)庫(kù)的函數(shù),執(zhí)行文本繁體轉(zhuǎn)簡(jiǎn)體操作。 需要在編譯時(shí)不鏈接動(dòng)態(tài)庫(kù),只在程序運(yùn)行時(shí)加載 OpenCC 動(dòng)態(tài)庫(kù)。
OpenCC 庫(kù)是使用 C++ 編寫(xiě)的繁簡(jiǎn)體轉(zhuǎn)換程序,提供 C 語(yǔ)言 API 接口。 開(kāi)源項(xiàng)目地址
CGO 技術(shù)是讓 Golang 語(yǔ)言使用 C 語(yǔ)言代碼的一種方式,可以在 Golang 程序編譯的時(shí)候鏈接 C 動(dòng)態(tài)庫(kù)。C 語(yǔ)言經(jīng)過(guò)數(shù)十年的發(fā)展,有豐富的開(kāi)源項(xiàng)目。在 Golang 生態(tài)還不是很完善的情況下,我們經(jīng)常需要使用一些成熟的C開(kāi)源項(xiàng)目。
Plugin 是 Golang 1.8 版本引入了一個(gè)新的插件系統(tǒng),允許程序員使用動(dòng)態(tài)鏈接庫(kù)構(gòu)建松散耦合的模塊化程序,在程序運(yùn)行時(shí)動(dòng)態(tài)加載和綁定。
本文循序漸進(jìn)地講解 2 種解決方案:
- 解決方案 1:使用 CGO 技術(shù),編譯時(shí)綁定 OpenCC 的接口。
- 解決方案 2:引入 Plugin 技術(shù),程序運(yùn)行時(shí)加載動(dòng)態(tài)庫(kù)。
解決方案1
方案 1 是最初的解決方案,使用 CGO 技術(shù),在編譯的時(shí)候綁定 OpenCC 的接口。
Golang -> CGO -> libopencc.so
編寫(xiě)CGO接口定義文件:
// opencc.h #include <stdlib.h> void* Opencc_New(const char *configFile); void* Opencc_Delete(void *id); const char *Opencc_Convert(void *id, const char *input); void Opencc_Free_String(char *p);
// opencc.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include "opencc/src/opencc.h" const char *Convert(const char *input, const char *config) { if(strlen(config) > 16) { return 0; } char configFile[256] = "/usr/share/opencc/"; strcat(configFile, config); strcat(configFile, ".json"); opencc_t p = opencc_open(configFile); char *out = opencc_convert_utf8(p, input, strlen(input)); out[strlen(input)] = '\0'; opencc_close(p); return out; } void Convert_free_string(char *p) { opencc_convert_utf8_free(p); } void* Opencc_New(const char *configFile) { return opencc_open(configFile); } void Opencc_Delete(void *id) { opencc_close(id); } const char *Opencc_Convert(void *id, const char *input) { char *output = opencc_convert_utf8(id, input, strlen(input)); output[strlen(input)] = '\0'; return output; } void Opencc_Free_String(char *p) { opencc_convert_utf8_free(p); }
// opencc.go package opencc import "unsafe" // #cgo LDFLAGS: -L${SRCDIR}/output/lib -lopencc // #include "opencc.h" import "C" func NewConverter(config string) unsafe.Pointer { return C.Opencc_New(C.CString(config)) } func Convert(p unsafe.Pointer, input string) string { inputChars := C.CString(input) outputChars := C.Opencc_Convert(p, inputChars) defer C.Opencc_Free_String(inputChars) defer C.Opencc_Free_String(outputChars) result := C.GoString(outputChars) return result } func Close(p unsafe.Pointer) { C.Opencc_Delete(p) } func ConvertOneTime(input string, config string) string { p := NewConverter(config) defer Close(p) return Convert(p, input) } func ConvertAsync(input string, config string, callback func(output string)) { go func() { callback(ConvertOneTime(input, config)) }() }
// test.go 調(diào)用OpenCC動(dòng)態(tài)庫(kù)的函數(shù)。 package main import "fmt" import "your/repository/go-opencc" const ( input = "中國(guó)鼠標(biāo)軟件打印機(jī)" config_s2t = "/usr/share/opencc/s2t.json" config_t2s = "/usr/share/opencc/t2s.json" ) func main() { fmt.Println("Test Converter class:") c := opencc.NewConverter(config_s2t) defer c.Close() output := c.Convert(input) fmt.Println(output) fmt.Println("Test Convert function:") s := opencc.Convert(input, config_s2t) fmt.Println(s) fmt.Println(opencc.Convert(s, config_t2s)) fmt.Println("Test ConvertAsync function:") retChan := make(chan string) opencc.ConvertAsync(input, config_s2t, func(output string) { retChan <- output }) fmt.Println(<- retChan) }
方案 1,可以正確鏈接 libopencc.so 文件,并成功執(zhí)行 Convert 函數(shù)進(jìn)行繁簡(jiǎn)體轉(zhuǎn)換。 但是有個(gè)問(wèn)題,該方案在 Mac 系統(tǒng)上不容易進(jìn)行編譯,需要在 Mac 系統(tǒng)里安裝 OpenCC 項(xiàng)目。假如調(diào)用 OpenCC 的項(xiàng)目有 10 人共同開(kāi)發(fā),就需要在 10 人的 Mac 電腦上進(jìn)行編譯,開(kāi)發(fā)協(xié)作困難,不方便部署。
解決方案2
引入 Plugin 技術(shù),程序運(yùn)行時(shí)加載動(dòng)態(tài)庫(kù)。
Golang -> Plugin -> libgo_opencc.so -> CGO -> libopencc.so
編寫(xiě) Plugin 動(dòng)態(tài)鏈接庫(kù)。
// opencc_lib.go package main import ( "unsafe" opencc "your/repository/go-opencc" ) type openccConverter string // NewConverter 創(chuàng)建Converter func (s openccConverter) NewConverter(config string) unsafe.Pointer { return opencc.NewConverter(config) } // Convert 轉(zhuǎn)換函數(shù) func (s openccConverter) Convert(p unsafe.Pointer, input string) string { return opencc.Convert(p, input) } // Close 釋放Converter占用的內(nèi)存資源(不再使用Converter了) func (s openccConverter) Close(p unsafe.Pointer) { opencc.Close(p) } // ConvertOneTime 轉(zhuǎn)換函數(shù)(轉(zhuǎn)換一次,該函數(shù)每次調(diào)用都會(huì)加載配置文件,有性能影響) func (s openccConverter) ConvertOneTime(input string, config string) string { return opencc.ConvertOneTime(input, config) } // OpenccConverter export symble var OpenccConverter openccConverter
編譯動(dòng)態(tài)庫(kù) build.sh 創(chuàng)建 output 目錄,編譯生成 ./output/lib/libgo_opencc.so 動(dòng)態(tài)庫(kù)。
#!/bin/bash mkdir -p output cd opencc ./build.sh cd .. cp -rf opencc/output/* ./output go build -buildmode=plugin -o ./output/lib/libgo_opencc.so ./lib/opencc_lib.go
使用 Plugin 加載 libgo_opencc.so,調(diào)用 OpenCC 的函數(shù)。
package main import ( "os" "plugin" "testing" "unsafe" "fmt" ) // 實(shí)現(xiàn) opencc_lib.go 的接口 type OpenccConverter interface { NewConverter(config string) unsafe.Pointer Convert(p unsafe.Pointer, input string) string Close(p unsafe.Pointer) ConvertOneTime(input string, config string) string } func TestOpenccSo(t *testing.T) { openccPlugin, pluginErr := plugin.Open("/your/path/to/go-opencc/output/lib/libgo_opencc.so") if pluginErr != nil { panic(pluginErr) } symbol, cerr := openccPlugin.Lookup("OpenccConverter") if cerr != nil { fmt.Errorf("%+v", cerr) os.Exit(1) } plug, ok := symbol.(OpenccConverter) if !ok { fmt.Errorf("unexpected type from module symbol") os.Exit(1) } config := "/usr/share/opencc/hk2s.json" pointer := plug.NewConverter(config) defer plug.Close(pointer) input := "傳統(tǒng)漢字" output := plug.Convert(pointer, input) fmt.Printf("output: %s", output) } // 運(yùn)行測(cè)試 TestOpenccSo,輸出 “傳統(tǒng)漢字”。
方案 2,實(shí)現(xiàn)了在程序運(yùn)行時(shí)通過(guò) Plugin 技術(shù)加載 libgo_opencc.so 動(dòng)態(tài)庫(kù),再由 libgo_opencc.so 鏈接到 libopencc.so,即可在 Mac、Linux 系統(tǒng)上編譯 Golang 程序,無(wú)需每臺(tái)開(kāi)發(fā)機(jī)都部署 OpenCC 項(xiàng)目。最終發(fā)布到生產(chǎn)環(huán)境時(shí),由編譯打包平臺(tái)將 libgo_opencc.so 和 libopencc.so 一起打包發(fā)布。
到此這篇關(guān)于Golang使用CGO與Plugin技術(shù)運(yùn)行加載C動(dòng)態(tài)庫(kù)的文章就介紹到這了,更多相關(guān)Go加載C動(dòng)態(tài)庫(kù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Go 語(yǔ)言 JSON 標(biāo)準(zhǔn)庫(kù)的使用
今天通過(guò)本文給大家介紹Go 語(yǔ)言 JSON 標(biāo)準(zhǔn)庫(kù)的使用小結(jié),包括序列化和反序列化的相關(guān)知識(shí),感興趣的朋友跟隨小編一起看看吧2021-10-10Go語(yǔ)言實(shí)現(xiàn)有規(guī)律的數(shù)字版本號(hào)的排序工具
這篇文章主要為大家詳細(xì)介紹了如何利用Go語(yǔ)言實(shí)現(xiàn)有規(guī)律的數(shù)字版本號(hào)的排序工具,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2023-01-01詳解golang中bufio包的實(shí)現(xiàn)原理
這篇文章主要介紹了詳解golang中bufio包的實(shí)現(xiàn)原理,通過(guò)分析golang中bufio包的源碼,來(lái)了解為什么bufio能夠提高文件讀寫(xiě)的效率和速度2018-01-01詳解Go語(yǔ)言實(shí)現(xiàn)線性查找算法和二分查找算法
線性查找又稱順序查找,它是查找算法中最簡(jiǎn)單的一種。二分查找,也稱折半查找,相比于線性查找,它是一種效率較高的算法。本文將用Go語(yǔ)言實(shí)現(xiàn)這兩個(gè)查找算法,需要的可以了解一下2022-12-12深入解析Go語(yǔ)言中for循環(huán)的寫(xiě)法
這篇文章主要介紹了Go語(yǔ)言中for循環(huán)的寫(xiě)法,是Golang入門(mén)學(xué)習(xí)中的基礎(chǔ)知識(shí),需要的朋友可以參考下2015-10-10

go語(yǔ)言實(shí)現(xiàn)將重要數(shù)據(jù)寫(xiě)入圖片中