Skip to content

Instantly share code, notes, and snippets.

@enkomio
Last active July 11, 2020 12:07
Show Gist options
  • Save enkomio/75ec59ea9dec8769070ad0b28b8ad720 to your computer and use it in GitHub Desktop.
Save enkomio/75ec59ea9dec8769070ad0b28b8ad720 to your computer and use it in GitHub Desktop.
An alternative method to load an Assembly
open System
open System.Reflection
open System.IO
/// Use the private method GetTypeByNameUsingCARules in order to load the Assembly. This method will in turn uses the internal
/// method: private static extern void GetTypeByNameUsingCARules(string name, RuntimeModule scope, ObjectHandleOnStack type);
let loadAssembly(filename: String, className: String, methodName: String, methodArguments: Object array) =
let bindingFlags = BindingFlags.Static ||| BindingFlags.NonPublic ||| BindingFlags.Public ||| BindingFlags.Instance
let assemblyName = AssemblyName.GetAssemblyName(Path.GetFullPath(filename))
let fullName = String.Format("{0},{1}", className, assemblyName.FullName)
let getTypeByNameUsingCARulesMethodInfo =
typeof<RuntimeTypeHandle>.GetMethods(bindingFlags)
|> Seq.filter(fun m -> m.GetParameters().Length = 2)
|> Seq.filter(fun m -> m.Name.Equals("GetTypeByNameUsingCARules", StringComparison.Ordinal))
|> Seq.head
let classRuntimeType = getTypeByNameUsingCARulesMethodInfo.Invoke(null, [|fullName; Assembly.GetEntryAssembly().ManifestModule|]) :?> Type
let methodToInvoke = classRuntimeType.GetMethod(methodName, bindingFlags)
let instance =
if methodToInvoke.IsStatic
then null
else Activator.CreateInstance(classRuntimeType)
methodToInvoke.Invoke(instance, methodArguments) |> ignore
[<EntryPoint>]
let main argv =
(**
Try to invoke the Hello method of the following C# class, compiled in the HelloDll.dll assembly:
using System;
namespace HelloDll
{
public class HelloClass
{
public void Hello()
{
Console.WriteLine("Hello!!");
}
}
}
*)
loadAssembly("HelloDll.dll", "HelloDll.HelloClass", "Hello", Array.empty<Object>)
0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment