dongwo1234 2018-04-27 20:51
浏览 98
已采纳

将通道参数传递给golang中的动态加载函数

I'm new to golang and golang plugins. I'm having trouble passing a chan object to this functions. If I switch to int it works. Not sure what exactly I am missing. Thanks for any help.

dataunit.go

package main

type DataUnit struct {
   i int
   s string
}

modcounter.go

package main
import ( 
  "fmt"
//  "strconv"
)
type module string 
//func (m module) RunMod(i int) {
func (m module) RunMod(in <-chan *DataUnit) {
    //fmt.Println("Hello Universe " + strconv.Itoa(i))
    fmt.Println("Hello Universe ")
        n := <-in
        fmt.Printf(n.s)
}
var Module module

modmain.go

package main

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


type DataUnit struct {
   i int
   s string
}

type Module interface {
        //RunMod(i int)
        RunMod(in <-chan *DataUnit)
}


func main() {


        out := make(chan *DataUnit, 2000)
        plug, err := plugin.Open("./modcounter.so")
        if err != nil {
                fmt.Printf("FATAL (plugin.Open): " + err.Error())
                os.Exit(1)
        }

        symModule, err := plug.Lookup("Module")
        if err != nil {
           fmt.Printf(err.Error())
           os.Exit(1)
        }

        var module Module
        module, ok:= symModule.(Module)
        if !ok {
                fmt.Println("unexpected type from module symbol")
                os.Exit(1)
        }

        //module.RunMod(5)
        module.RunMod(out)
}

go build -buildmode=plugin -o modcounter.so modcounter.go dataunit.go
go build modmain.go dataunit.go

./modmain
unexpected type from module symbol

  • 写回答

2条回答 默认 最新

  • duanfu3390 2018-04-28 12:14
    关注

    In go is possible to pass channels of objects!!

    For example, if you to use <-chan http.Header will works fine. The question is that the params must be shared between modules and application. So if you reallocate DataUnit for another package will work.

    My test was structured like:

    enter image description here

    My interface:

    //in modmain.go
    type Module interface {
        RunMod(in <-chan *mydata.DataUnit)
    }
    

    My module:

    //in modcounter.go
    func (m module) RunMod(in <-chan *mydata.DataUnit) {
        fmt.Println("Hello Universe ")
        n := <-in
        fmt.Printf("%v", n.S)
    }
    

    My data:

    //in dataunit.go
    type DataUnit struct {
        I int    //export field
        S string //export field
    }
    

    The result: enter image description here

    P.S.: Docker with golang 1.10 was used for tests.

    #in Dockerfile
    FROM golang:1.10
    COPY . /go/
    RUN export GOPATH=$GOPATH:/go/
    RUN cd /go/src/mydata && go build dataunit.go
    RUN cd /go/src/app && go build modmain.go
    RUN cd /go/src/app && go build -buildmode=plugin -o modcounter.so modcounter.go
    WORKDIR /go/src/app
    RUN ls -l
    CMD ["/go/src/app/modmain"]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?