作用:动态加载外部 go 文件
加载方式:
1.编译go程序
GOOS=linux GOARCH=amd64 CGO_ENABLED=1 GOPROXY=https://goproxy.cn,direct GO111MODULE=on go build -gcflags="all=-N -l" main.go
此处注意:使用go plugin时 CGO_ENABLED必须开启,添加 -gcflags="all=-N -l"
2.定义加载的 struct和方法
示例如下:
import (
"C"
"reflect"
)
type Test struct {
ID string `json:"id"`
Name string `json:"name"`
}
func GetType() reflect.Type {
return reflect.TypeOf(&Test{})
}
func GetName() string {
return "test"
}
3.编译外部go文件为 .so文件
go build -buildmode=plugin -gcflags="all=-N -l" -o extend extend/*.go
4.加载编译完成的 .so文件
testFile:="./test.so"
testFuncName := "GetType"
p, err := plugin.Open(testFile)
if err != nil {
fmt.Println(err)
}
testFunc, err := p.Lookup(testFuncName )
if err != nil {
fmt.Println(err)
}
//获取 struct 类型,后面可以用该类型使用反射生成对象和slice等
_type := testFunc.(func() reflect.Type)()
4.使用struct类型生成slice,比如[]Test
sliceType := reflect.SliceOf(_type) testSlice:=reflect.MakeSlice(sliceType, 0, 0).Interface()
1084

被折叠的 条评论
为什么被折叠?



