vfunc.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package vfunc
  2. import (
  3. "reflect"
  4. "unsafe"
  5. )
  6. // UCastFunc create function caller by unsafe pointer
  7. func UCastFunc(fn interface{}) func(...interface{}) interface{} {
  8. f := fn
  9. fRefl := reflect.ValueOf(f)
  10. return *(*func(...interface{}) interface{})(unsafe.Pointer(fRefl.Pointer()))
  11. }
  12. // NCastFunc creates a function caller by Reflection
  13. func NCastFunc(fn interface{}) func(...interface{}) interface{} {
  14. fnRefl := reflect.ValueOf(fn)
  15. ret := func(args ...interface{}) interface{} {
  16. nargs := []reflect.Value{}
  17. for _, a := range args {
  18. nargs = append(nargs, reflect.ValueOf(a))
  19. }
  20. return fnRefl.Call(nargs)[0].Interface()
  21. }
  22. return ret
  23. }
  24. //CastFunc creates a function caller by MakeFunc
  25. func RCastFunc(fn interface{}) func(...interface{}) interface{} {
  26. var dummy func(...interface{}) interface{}
  27. fnRefl := reflect.ValueOf(fn)
  28. myFunci := reflect.MakeFunc(reflect.TypeOf(dummy), func(args []reflect.Value) (results []reflect.Value) {
  29. // Expect variadic so
  30. var nargs []reflect.Value
  31. for _, v := range args[0].Interface().([]interface{}) {
  32. nargs = append(nargs, reflect.ValueOf(v))
  33. }
  34. ret := fnRefl.Call(nargs)[0].Interface()
  35. return []reflect.Value{reflect.ValueOf(&ret).Elem()}
  36. // Convert the fucker"
  37. }).Interface().(func(...interface{}) interface{})
  38. return myFunci
  39. }