Home >Backend Development >Golang >How Can I Share Custom Data Types Between a Go Plugin and Its Application?
In Go plugins, it's possible to share custom data types between the plugin and the application, but not through direct type assertion.
To define shared types, create them in a separate package and import it into both the plugin and the main application. For example:
Shared Type Package:
<code class="go">package shared type Person struct { Name string }</code>
Plugin Code:
<code class="go">package main import ( "shared" ) var P = shared.Person{Name: "Emma"}</code>
Main Application Code:
<code class="go">package main import ( "fmt" "plugin" "shared" "os" ) func main() { plug, err := plugin.Open("./plugin.so") if err != nil { fmt.Println(err) os.Exit(1) } // Lookup shared type symbol sym, err := plug.Lookup("P") if err != nil { fmt.Println(err) os.Exit(1) } // Type-assert symbol into shared type var p shared.Person p, ok := sym.(shared.Person) if !ok { fmt.Println("Wrong symbol type") os.Exit(1) } // Use shared type as expected fmt.Println(p.Name) }</code>
When looking up variable symbols from a plugin, the result is a pointer to the variable, even if it's a non-pointer type. This allows modification of the variable's value from the plugin.
By using shared types defined in a separate package, it's possible to pass custom data types between a Go plugin and an application, enabling efficient data exchange and extending the plugin's capabilities.
The above is the detailed content of How Can I Share Custom Data Types Between a Go Plugin and Its Application?. For more information, please follow other related articles on the PHP Chinese website!