duanhao1004 2019-01-31 22:00
浏览 103
已采纳

如何调用通过反射获得的闭包函数?

I'm experimenting with using Go's reflection library and have come to an issue I cannot figure out: How does one call on a function returned from calling a closure function via reflection? Is it possible to basically have a sequence of:

func (f someType) closureFn(i int) int {
  return func (x int) int {
     return x+i
  }
}
...

fn := reflect.ValueOf(&f).MethodByName("closureFn")
val := append([]reflect.Value{}, reflect.ValueOf(99))
fn0 := fn.Call(val)[0]
fn0p := (*func(int) int)(unsafe.Pointer(&f0))
m := (*fn0p)(100)

Which should get m to equal 199?

The following is the simplified code that demonstrates the issue. The call to the "dummy" anonymous function works ok, as does the reflective call to the closure. However attempts at calling on the closure return fail with a nil pointer (the flag set on the address of the Value in the debugger is 147, which comes down to addressable). Any suggestions on what's going on, or if it's at all possible are welcome.

Link to playground: https://play.golang.org/p/0EPSCXKYOp0

package main

import (
    "fmt"
    "reflect"
    "unsafe"
)

// Typed Struct to hold the initialized jobs and group Filter function types
type GenericCollection struct {
    jobs []*Generic
}

type Generic func (target int) int

func main() {
    jjf := &GenericCollection{jobs: []*Generic{}}
    jjf.JobFactoryCl("Type", 20)
}


// Returns job function with closure on jobtype
func (f GenericCollection) Job_by_Type_Cl(jobtype int) (func(int) int) {
    fmt.Println("Job type is initialized to:", jobtype)

    // Function to return
    fc := func(target int) int {
        fmt.Println("inside JobType function")
            return target*jobtype
    }
    return fc
}

// Function factory
func (f GenericCollection) JobFactoryCl(name string, jobtype int) (jf func(int) int) {

    fn := reflect.ValueOf(&f).MethodByName("Job_by_" + name + "_Cl")
    val := append([]reflect.Value{}, reflect.ValueOf(jobtype))
    if fn != reflect.ValueOf(nil) {

        // Reflected function -- CALLING IT FAILS
        f0 := fn.Call(val)[0]
        f0p := unsafe.Pointer(&f0)

        //Local dummy anonymous function - CALLING IS OK
        f1 := func(i int) int {
            fmt.Println("Dummy got", i)
            return i+3
        }
        f1p := unsafe.Pointer(&f1)

        // Named function

        pointers := []unsafe.Pointer{f0p, f1p}

        // Try running f1 - OK
        f1r := (*func(int) int)(pointers[1])
        fmt.Println((*f1r)(1))
        (*f1r)(1)

        // Try calling f0 - FAILS. nil pointer dereference
        f0r := (*func(int) int)(pointers[0])
        fmt.Println((*f0r)(1))

        jf = *f0r
    }
    return jf
}
  • 写回答

1条回答 默认 最新

  • duanhuan6336 2019-02-01 01:08
    关注

    Type assert the method value to a function with the appropriate signature. Call that function.

    First example from the question:

    type F struct{}
    
    func (f F) ClosureFn(i int) func(int) int {
        return func(x int) int {
            return x + i
        }
    }
    
    func main() {
        var f F
        fn := reflect.ValueOf(&f).MethodByName("ClosureFn")
    
        fn0 := fn.Call([]reflect.Value{reflect.ValueOf(99)})[0].Interface().(func(int) int)
        fmt.Println(fn0(100))
    
        // It's also possible to type assert directly 
        // the function type that returns the closure.
        fn1 := fn.Interface().(func(int) func(int) int)
        fmt.Println(fn1(99)(100))
    }
    

    Run it on the Playground

    Second example from the question:

    func (f GenericCollection) JobFactoryCl(name string, jobtype int) func(int) int {
        jf := reflect.ValueOf(&f).MethodByName("Job_by_" + name + "_Cl").Interface().(func(int) func(int) int)
        return jf(jobtype)
    }
    
    func main() {
       jjf := &GenericCollection{jobs: []*Generic{}}
       jf := jjf.JobFactoryCl("Type", 20)
       fmt.Println(jf(10))
    }
    

    Run it on the Playground

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。