I've a following plugin:
package main
type Test struct {
Id string
}
func (test *Test) GetId() string {
return test.Id
}
var V Test
I'm importing it within my app:
package main
import (
"fmt"
"plugin"
)
func main() {
p, err := plugin.Open("test.so")
if err != nil {
panic(err)
}
v, err := p.Lookup("V")
if err != nil {
panic(err)
}
fmt.Println(v)
}
Unfortunately I'm not able to call v.getId()
on it - is there a way to expose all functions that are set on the given struct?
Lookup
returns a Symbol
, which is just an empty interface. In order to use this you need to assert the type you want. The documentation for Symbol
example shows both symbols asserted to the expected types:
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"
To do that in your program, create the type you want, which in this case is an interface because you're looking for a particular method set (see the "Tour of Go" section on interfaces, esp implicit implementation and type assertion)
Here we create the V
interface in the main program to define the method we want, than use a type assertion on the symbol returned from Lookup
:
type V interface {
GetId() string
}
func main() {
p, err := plugin.Open("plugin.so")
if err != nil {
panic(err)
}
s, err := p.Lookup("V")
if err != nil {
panic(err)
}
v := s.(V)
fmt.Println(v.GetId())
}