简介
Go 的 plugin 技术,在 Go 1.8 版本就有了,现在有要求,索性就自己看了下原理,然后写了下面demo
项目地址: https://github.com/acelj/tookit/tree/master/02go-plugin
注意事项
编写go-plugin注意事项:
- 代码中必须是main包
- 不需要main函数
- 必须有导出的变量或者方法
Code
package main
import "fmt"
// go build --buildmode=plugin -o hello.so hello.go
func Hello() {
fmt.Println("Hello From plugin...")
}
func Test(a, b string) (c, d int) {
fmt.Println("a = ", a)
fmt.Println("b = ", b)
c, d = 100, 200
return c, d
}
package main
import (
"fmt"
"os"
"plugin"
)
// go run main.go
func main() {
p, err := plugin.Open("./hello.so")
if err != nil {
fmt.Println("error open plugin: ", err)
os.Exit(-1)
}
s, err := p.Lookup("Hello")
if err != nil {
fmt.Println("error lookup Helllo: ", err)
os.Exit(-1)
}
if myhello, ok := s.(func()); ok {
myhello()
}
s1, err := p.Lookup("Test")
if err != nil {
fmt.Println("error lookup Test: ", err)
os.Exit(-1)
}
if myfunc, ok := s1.(func(string, string) (int, int)); ok {
a, b := myfunc("111", "222")
fmt.Printf("a = %d, b = %d\n", a, b)
}
}