jeudi 31 janvier 2019

How to call closure function obtained through reflection?

I 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 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
}





Aucun commentaire:

Enregistrer un commentaire