CodeBlanks Logo Icon CodeBlanks

Loading a plugin

Learn to load a plugin with plugin.Open.

Loading a plugin

plugin.Open loads the file; opening the same file again returns the same *plugin.Plugin. Then you ask for a symbol by name with Lookup:

p, err := plugin.Open("selam.so")
if err != nil { log.Fatal(err) }
sym, err := p.Lookup("Selam")
if err != nil { log.Fatal(err) }

Error checking is required at both steps.

Opening the same plugin again

A plugin is loaded only once per process; its init functions also run once. Changing the file and reopening it doesn't bring in the new code. If hot reloading is needed you must build with a different file name or use a separate process.

Practice Open and look up

Write loadSymbol(path, name string) error: return the error from plugin.Open(path), then the error from p.Lookup(name). In main, print the result of loadSymbol("x.so", "Selam") != nil.

Starter code

main.go
package main

import (
    "fmt"
    "plugin"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "fmt"
    "plugin"
)

func loadSymbol(path, name string) error {
    p, err := plugin.Open(path)
    if err != nil {
        return err
    }
    _, err = p.Lookup(name)
    return err
}

func main() {
    fmt.Println(loadSymbol("x.so", "Selam") != nil)
}

Expected output

true

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does <code>Lookup</code> return?

  • A plugin.Symbol and an error Correct answer
  • Only a function
  • A file path
  • A goroutine

Explanation: Lookup returns a plugin.Symbol (really an any) and an error; you type-assert it to the real type before use.

2 Ask for the symbol

Question
sym, err := p.____("Selam")
Answer
sym, err := p.Lookup("Selam")

Explanation: Lookup finds an exported symbol by name.

3 Loading steps

Term Meaning
1. plugin.Open Load the file
2. Lookup Find the symbol
3. Type assertion Convert to the real type
4. Call Use the function

All lessons in Advanced