Created
January 16, 2022 03:07
-
-
Save AntiKnot/179b8b0854215a04512587badf528506 to your computer and use it in GitHub Desktop.
go Plugin demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| func Add(x int, y int) int { | |
| z := x + y | |
| return z | |
| } | |
| func Minus(x int, y int) int { | |
| z := x - y | |
| return z | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "fmt" | |
| "log" | |
| "plugin" | |
| ) | |
| func loadPlugin(filename string) (func(int, int) int, func(int, int) int) { | |
| p, err := plugin.Open(filename) | |
| if err != nil { | |
| log.Fatalf("cannot load plugin %v", filename) | |
| } | |
| xminusf, err := p.Lookup("Minus") | |
| if err != nil { | |
| log.Fatal("cannot load xminusf in %v", filename) | |
| } | |
| minusf := xminusf.(func(int, int) int) | |
| xaddf, err := p.Lookup("Add") | |
| if err != nil { | |
| log.Fatal("cannot load xaddf in %v", filename) | |
| } | |
| addf := xaddf.(func(int, int) int) | |
| return addf, minusf | |
| } | |
| func main() { | |
| addf, minusf := loadPlugin("arithmetic.so") | |
| r1 := addf(1, 1) | |
| r2 := minusf(1, 1) | |
| fmt.Printf("add 1 1 res is %v\n", r1) | |
| fmt.Printf("minus 1 1 res is %v\n", r2) | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| build: | |
| go build -buildmode=plugin arithmetic.go | |
| go build calculate.go | |
| run: | |
| ./calculate |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment