dongtieshang5429
2018-05-05 23:21
浏览 74
已采纳

是否可以在go插件和应用程序之间共享自定义数据类型?

I know that it is possible to look up for go-plugin symbols that were exported and type assert them into an interface. However, I wonder if is there a way to type assert them into a struct, for example. Is there a way to do it?

For example:

plugin.go

package main

type Person struct {
    Name string
}

var (
    P = Person{
        Name: "Emma",
    }
)

app.go

package main

import (
    "fmt"
    "plugin"
    "os"
)

func main() {
    plug, err := plugin.Open("./plugin.so")
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    sym, err := plug.Lookup("P")
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    var p Person
    p, ok := sym.(Person)
    if !ok {
        fmt.Println("Wrong symbol type")
        os.Exit(1)
    }

    fmt.Println(p.Name) 
}

The symbol P, which is a Person, is found when plug.Lookup is called. However, I can't type-assert P into Person, I get an execution time error. In this example, "Wrong symbol type".

Is there a way to achieve this or the only way to share data between the plugin and the application is using interfaces?

Thanks.

图片转代码服务由CSDN问答提供 功能建议

我知道可以查找导出的go-plugin符号并将其断言为< EM>接口。 但是,我想知道是否有一种方法可以将它们断言为一个结构。 有办法吗?

例如:

plugin.go \ n

 包main 
 
type Person struct {
 Name string 
} 
 
var(
 P = Person {
 Name:“ Emma”,
} 
)
    
 
 

app.go

  package main 
 
import(
“ fmt  “ 
” plugin“ 
” os“ 
)
 
func main(){
 plug,err:= plugin.Open(” ./ plugin.so“)
 if err!= nil {\  n fmt.Println(err)
 os.Exit(1)
} 
 sym,err:= plug.Lookup(“ P”)
 if err!= nil {
 fmt.Println(err)\  n os.Exit(1)
} 
 var p Person 
p,ok:= sym。(Person)
 if!ok {
 fmt.Println(“ Wrong symbol type”)
 os.Exit(  1)
} 
 
 fmt.Println(p.Name)
} 
   
 
 

符号P,它是 Person 调用 plug.Lookup 时找到em>。 但是,我无法将P输入为 Person ,但是出现执行时间错误。 在此示例中,“错误的符号类型”

是否有实现此目的的方法,还是在插件和应用程序之间共享数据的唯一方法? 接口?

谢谢。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题