25

Golang标准库——plugin

 3 years ago
source link: https://studygolang.com/articles/31185
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

plugin

plugin包实现Go插件的加载和符号解析。

目前,plugin仅在Linux上有效。

plugin是Go主程序包,具有导出的函数和变量,这些函数和变量已使用以下命令构建:

go build -buildmode=plugin

首次打开插件时,将调用尚未包含在程序中的所有软件包的init函数。 主要功能未运行。 插件仅初始化一次,无法关闭。

type Plugin

type Plugin struct {
    pluginpath string
    err        string        // set if plugin failed to load
    loaded     chan struct{} // closed when loaded
    syms       map[string]interface{}
}

Plugin是一个已加载的Go插件。

func Open

func Open(path string) (*Plugin, error)

Open打开一个Go插件。 如果已经打开路径,则返回现有的* Plugin。 对于多个goroutine并发使用是安全的。

func (*Plugin) Lookup

func (p *Plugin) Lookup(symName string) (Symbol, error)

Lookup在插件p中搜索名为symName的符号。 符号是任何导出的变量或函数。 如果找不到该符号,它将报告错误。 对于多个goroutine并发使用是安全的。

type Symbol

type Symbol interface{}

Symbol是指向变量或函数的指针。

例如,定义为

package main

// // No C code needed.
import "C"

import "fmt"

var V int

func F() { fmt.Printf("Hello, number %d\n", V) }

可以加载打开功能,然后可以访问导出的软件包符号V和F

p, err := plugin.Open("plugin_name.so")
if err != nil {
    panic(err)
}
v, err := p.Lookup("V")
if err != nil {
    panic(err)
}
f, err := p.Lookup("F")
if err != nil {
    panic(err)
}
*v.(*int) = 7
f.(func())() // prints "Hello, number 7"

有疑问加站长微信联系

iiUfA3j.png!mobile

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK