2020-10-02: How to write a plugin in golang?

Fu Ge's answer 2020-10-02: #福大建筑师日一题#
Simple answer:
buildmode=plugin
plugin.Open
p.Lookup

Intermediate answer: The
golang plugin is a software package compiled with the compilation flag of -buildmode=plugin to generate shared library (.so) library files. The functions and variables exported in the Go package are displayed as ELF symbols, and you can use the pluginpackage in golang to find and bind them at runtime in another golang program .
First write such a piece of plugin code:

package main

import "fmt"

// 包含一个简单函数的模块
func Add(a int, b int) int {
    
    
    fmt.Printf("\nAdding a=%d and b=%d", a, b)
    return a + b
}

Use the following command to compile into plugin:
go build -buildmode=plugin -o math.so

Then you can load and call the compiled plugin in another golang code:

// 加载plugin
plugins, err := filepath.Glob("math.so")
if err != nil {
    
    
    panic(err)
}
fmt.Printf("Loading plugin %s", plugins[0])
p, err := plugin.Open(plugins[0])
if err != nil {
    
    
    panic(err)
}

// 查找叫Add的函数
symbol, err := p.Lookup("Add")
if err != nil {
    
    
    panic(err)
}
addFunc, ok := symbol.(func(int, int) int)
if !ok {
    
    
    panic("Plugin has no 'Add(int)int' function")
}

// 调用函数
addition := addFunc(3, 4)
fmt.Printf("\nAddition is:%d", addition)

comment

Guess you like

Origin blog.csdn.net/weixin_48502062/article/details/108903192