Go 1.8 的 plugin 使用

前端之家收集整理的这篇文章主要介绍了Go 1.8 的 plugin 使用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Go 1.8 为我们提供了一个创建共享库的新工具,称为 Plugins!让我们来创建和使用一个插件。 目前的插件只能在 Linux 和 Darwin (1.8 正式版因为 Bug 已移除支持)上工作。

安装 1.8 beta1,不做说明.

创建一个插件方法到 aplugin.go:

  1. package main
  2.  
  3. func Add(x,y int) int {
  4. return x+y
  5. }
  6.  
  7. func Subtract(x,y int) int {
  8. return x-y
  9. }

然后构建插件:

运行下面命令构建插件:

  1. go build -buildmode=plugin

构建指定文件插件 aplugin.go 到 aplugin.so:

  1. go build -buildmode=plugin -o aplugin.so aplugin.go

加载插件:

  1. p,_ := plugin.Open("./aplugin.so")
  2. //p,err := plugin.Open("./aplugin.so")

call 插件:

  1. add,_ := p.Lookup("Add")
  2. sub,_ := p.Lookup("Subtract")

使用插件:

  1. sum := add.(func(int,int) int)(11,2)
  2. fmt.Println(sum)
  3. subt := sub.(func(int,2)
  4. fmt.Println(subt)

另外源码测试中有:

  1. go build -buildmode=c-shared

应该可以支持 c 语言构建插件

猜你在找的Go相关文章