我用 Go 編寫(xiě)了一個(gè)插件生成器?;刭?gòu)是開(kāi)放的。該項(xiàng)目在一些臨時(shí)文件中創(chuàng)建了一些 Go 代碼,定義了一個(gè)從命令行參數(shù)中獲取的函數(shù),將該代碼編譯成一個(gè)插件,加載該插件,獲取其中的函數(shù),并使用參數(shù)調(diào)用它,然后打印結(jié)果。我們希望能夠處理多個(gè)函數(shù)和多個(gè)插件。例如,SUMbody 的函數(shù), body 的 return x+y;函數(shù);等等。PRODreturn x*y我不希望生成的代碼始終使用常量名稱 FUNCTION。生成的 .go 文件不能包含名稱在運(yùn)行時(shí)給出的函數(shù),即funame 下面代碼中的 my 嗎?Go 語(yǔ)言是否有某些功能禁止這樣做?//TODO: Investigate how to relax the name FUNCTION into a variabletype Xinterface interface { FUNCTION(x int, y int) int}用法示例:$ go run forbasile.go SUM 'return x+y' 3 5func(s sum) FUNCTION (x int, y int) int { start of sum: x=3, y=5131 bytes written successfully/tmp/go-build104174513/b001/execompiling plugin[]loading modulelooking up symbolchecking module8Generated code: /tmp/SUM.goGenerated object file: /tmp/SUM.so$ go run forbasile.go SUMSQUARE 'return x*x + y*y' 3 4func(s sumsquare) FUNCTION (x int, y int) int { start of sumsquare: x=3, y=4161 bytes written successfully/tmp/go-build555823501/b001/execompiling plugin[]loading modulelooking up symbolchecking module25Generated code: /tmp/SUMSQUARE.goGenerated object file: /tmp/SUMSQUARE.so
1 回答

侃侃無(wú)極
TA貢獻(xiàn)2051條經(jīng)驗(yàn) 獲得超10個(gè)贊
godoc
Symbol 是指向變量或函數(shù)的指針。
例如,一個(gè)插件定義為
package main
import "fmt"
func F() { fmt.Printf("Hello, number %d\n", V) }
可以加載Open函數(shù),然后可以訪問(wèn)導(dǎo)出的包符號(hào)V和F
p, err := plugin.Open("plugin_name.so")
if err != nil {
? ? panic(err)
}
f, err := p.Lookup("F")
if err != nil {
? ? panic(err)
}
f.(func())() // prints "Hello, number 7"
“F”只是一個(gè)字符串,因此您無(wú)論如何都可以在運(yùn)行時(shí)更改它的值。
- 1 回答
- 0 關(guān)注
- 134 瀏覽
添加回答
舉報(bào)
0/150
提交
取消