How Can I Share Custom Data Types Between a Go Plugin and Its Application?

Patricia Arquette
Release: 2024-10-25 08:40:29
Original
814 people have browsed it

How Can I Share Custom Data Types Between a Go Plugin and Its Application?

Sharing Custom Data Types Between a Go Plugin and an Application

In Go plugins, it's possible to share custom data types between the plugin and the application, but not through direct type assertion.

Shared Data Types in Separate Packages

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>
Copy after login

Plugin Code:

<code class="go">package main

import (
    "shared"
)

var P = shared.Person{Name: "Emma"}</code>
Copy after login

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>
Copy after login

Non-Pointer Types and Pointer Symbols

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.

Conclusion

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!