开发者

Retrieve MethodInfo of a F# function

I w开发者_StackOverflowould like to write a function that takes a function f as an argument and returns the System.Reflection.MethodInfo associated to f.

I'm not quite sure if it is feasible or not.


So, I finally found a solution. Very hacky, but hey! It works! (edit: in Debug mode only).

let Foo (f:S -> A[] -> B[] -> C[] -> D[] -> unit) =
    let ty     = f.GetType()
    let argty  = [|typeof<S>; typeof<A[]>; typeof<B[]>; typeof<C[]>;typeof<D[]>|]
    let mi     = ty.GetMethod("Invoke", argty)
    let il     = mi.GetMethodBody().GetILAsByteArray()
    let offset = 9//mi.GetMethodBody().MaxStackSize

    let token  = System.BitConverter.ToInt32(il, offset)    
    let mb     = ty.Module.ResolveMethod(token)

    match Expr.TryGetReflectedDefinition mb with
    | Some ex -> printfn "success %A" e
    | None ->  failwith "failed"

It works well, even if f is defined in another assembly (.dll) or in the same where the call of Foo happens. It's not fully general yet since I have to define what argty is, but I'm sure I can write a function that does it.

Turns out after writing this code that Dustin have a similar solution for the same issue, albeit in C# (see it here).

EDIT: So here's an usage example:

open System
open Microsoft.FSharp.Quotations

[<ReflectedDefinition>]
let F (sv:int) (a:int[]) (b:int[]) (c:int[]) (d:int[]) =
    let temp = a.[2] + b.[3]
    c.[0] <- temp
    ()

let Foo (f:S -> A[] -> B[] -> C[] -> D[] -> unit) =
    let ty     = f.GetType()
    let arr    = ty.BaseType.GetGenericArguments()
    let argty  = Array.init (arr.Length-1) (fun i -> arr.[i])

    let mi     = ty.GetMethod("Invoke", argty)
    let il     = mi.GetMethodBody().GetILAsByteArray()
    let offset = 9
    let token  = System.BitConverter.ToInt32(il, offset)
    let mb     = ty.Module.ResolveMethod(token)
    mb

let main () =
  let mb = Foo F
  printfn "%s" mb.Name

  match Expr.TryGetReflectedDefinition mb with
  | None -> ()
  | Some(e) -> printfn "%A" e

do main ()

What it does is printing name of F, and its AST if the function is a reflected definition.

But after further investigation, it happens that this hack only works in debug mode (and F has to be a function value as well as a top level definition), so might as well say that it's an impossible thing to do.

Here's the IL code of the FSharpFunc's Invoke method in both debug/release build:

DEBUG mode:

.method /*06000007*/ public strict virtual 
        instance class [FSharp.Core/*23000002*/]Microsoft.FSharp.Core.Unit/*01000006*/ 
        Invoke(int32 sv,
               int32[] a,
               int32[] b,
               int32[] c,
               int32[] d) cil managed
// SIG: 20 05 12 19 08 1D 08 1D 08 1D 08 1D 08
{
  // Method begins at RVA 0x21e4
  // Code size       16 (0x10)
  .maxstack  9
  IL_0000:  /* 00   |                  */ nop
  IL_0001:  /* 03   |                  */ ldarg.1
  IL_0002:  /* 04   |                  */ ldarg.2
  IL_0003:  /* 05   |                  */ ldarg.3
  IL_0004:  /* 0E   | 04               */ ldarg.s    c
  IL_0006:  /* 0E   | 05               */ ldarg.s    d
  IL_0008:  /* 28   | (06)000001       */ call       void Program/*02000002*/::F(int32,
                                                                                 int32[],
                                                                                 int32[],
                                                                                 int32[],
                                                                                 int32[]) /* 06000001 */
  IL_000d:  /* 00   |                  */ nop
  IL_000e:  /* 14   |                  */ ldnull
  IL_000f:  /* 2A   |                  */ ret
} // end of method mb@25::Invoke

RELEASE mode:

method public strict virtual instance class [FSharp.Core]Microsoft.FSharp.Core.Unit 
        Invoke(int32 sv,
               int32[] a,
               int32[] b,
               int32[] c,
               int32[] d) cil managed
{
  // Code size       28 (0x1c)
  .maxstack  7
  .locals init ([0] int32 V_0)
  IL_0000:  nop
  IL_0001:  ldarg.2
  IL_0002:  ldc.i4.2
  IL_0003:  ldelem     [mscorlib]System.Int32
  IL_0008:  ldarg.3
  IL_0009:  ldc.i4.3
  IL_000a:  ldelem     [mscorlib]System.Int32
  IL_000f:  add
  IL_0010:  stloc.0
  IL_0011:  ldarg.s    c
  IL_0013:  ldc.i4.0
  IL_0014:  ldloc.0
  IL_0015:  stelem     [mscorlib]System.Int32
  IL_001a:  ldnull
  IL_001b:  ret
} // end of method mb@25::Invoke

You can see that in release mode, the compiler inlines code of F into the Invoke method, so the information of calling F (and the possibility to retrieve the token) is gone..


Does the program below help?

module Program

[<ReflectedDefinition>]
let F x =
    x + 1

let Main() =
    let x = F 4    
    let a = System.Reflection.Assembly.GetExecutingAssembly()
    let modu = a.GetType("Program")
    let methodInfo = modu.GetMethod("F")
    let reflDefnOpt = Microsoft.FSharp.Quotations.Expr.TryGetReflectedDefinition(methodInfo)
    match reflDefnOpt with
    | None -> printfn "failed"
    | Some(e) -> printfn "success %A" e

Main()    


This is not (easily) possible. The thing to note is that when you write:

let printFunctionName f =
    let mi = getMethodInfo f
    printfn "%s" mi.Name

Parameter 'f' is simply an instance of type FSharpFunc<,>. So the following are all possible:

printFunctionName (fun x -> x + 1)    // Lambda expression
printFunctionName String.ToUpper      // Function value
printFunctionName (List.map id)       // Curried function
printFunctionNAme (not >> List.empty) // Function composition

In either case there is no straightforward answer to this


I don't know if there is a general answer for any kind of function, but if your function is simple ('a -> 'b) then you could write

let getMethodInfo (f : 'a -> 'b) = (FastFunc.ToConverter f).Method

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜