【问题标题】:How to call closure function obtained through reflection?如何调用反射得到的闭包函数?
【发布时间】:2019-02-01 22:54:37
【问题描述】:

我正在尝试使用 Go 的反射库,但遇到了一个我无法弄清楚的问题:如何对通过反射调用闭包函数返回的函数进行调用?是否有可能基本上有一个序列:

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)

哪个应该让 m 等于 199?

以下是演示该问题的简化代码。对“虚拟”匿名函数的调用可以正常工作,对闭包的反射调用也是如此。然而,尝试调用闭包返回失败并返回一个 nil 指针(调试器中值的地址上设置的标志是 147,归结为可寻址)。 欢迎对正在发生的事情或是否有可能提出任何建议。

游乐场链接: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
}

【问题讨论】:

  • 不要盲目地尝试使用unsafe.Pointer 进行转换。我还不确定你到底想要什么,但是Call 返回了reflect.Value 的一部分,所以你可以随意断言,或者继续使用反射值。
  • 看起来map[string]func(int) int 在您显示的设置中更容易使用。

标签: go reflection closures


【解决方案1】:

Type assert method value 到具有适当签名的函数。调用那个函数。

问题的第一个例子:

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

问题的第二个例子:

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

【讨论】:

  • 谢谢!将值包装到接口中并将其作为函数声明的巧妙技巧。小问题:为什么在我的代码中,指针调用对闭包 fn 不起作用,而对匿名函数却起作用? IE。有什么问题: f0r := (*func(int) int)(unsafe.Pointer(&f0)) 然后调用使用: (*f0r)(10)
  • f0 是函数的反射值,而不是函数本身。您需要在 reflect.Value 中添加一个偏移量以获取该函数。不要那样做。使用此答案中显示的受支持的 API。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-24
  • 1970-01-01
相关资源
最近更新 更多