3

I'm trying to consume an F# assembly from Fsi, but can't seem to find a way to get a list of methods defined in a module so I can call them.

Here's a sample file I'm trying to do this with. In following the "exposing methods that are cross language friendly", I've added a namespace to the top of the file and added a module to contain the let bound methods that were there previously. I'd like to avoid moving everything into static classes if possible.

Can I use reflection, or write the module in another way that helps me find the available methods and proper casing of the methods?

Community
  • 1
  • 1
Maslow
  • 18,464
  • 20
  • 106
  • 193

1 Answers1

3

If I correctly understood the problem, I would proceed as follows:

1) Get the desired assembly. For example, the assembly that is currently being executed can be obtained by

System.Reflection.Assembly.GetExecutingAssembly

2) Then I would take all the types defined in the obtained assembly by calling GetTypes. If you want to filter out modules you could write something like.

let modules = Array.filter (fun x -> FSharpType.IsModule x) (assembly.GetTypes())

The documentation for the FSharpType class can be found here. It is included in the Microsoft.FSharp.Reflection namespace.

3) After, you can obtain the methods in a module by calling GetMethods method on a single module. For example, to print them all, you could write something like:

let methods = [| for t in modules do for m in t.GetMethods() -> m |]
for m in methods do
    printfn "%A" m

methods is an array containing MethodInfo elements. GetMethods takes an optional parameter of type BindingFlags that can filter out some methods. Take a look at the documentation.

You can also invoke actions by calling the Invoke method on a MethodInfo object.

Hope this was useful.

Nikos Baxevanis
  • 10,868
  • 2
  • 46
  • 80
MSX
  • 359
  • 1
  • 14