Skip to content

Instantly share code, notes, and snippets.

@thewilsonator
Created April 25, 2019 15:28
Show Gist options
  • Save thewilsonator/654066efce91ea02e3e601bdfdd0e751 to your computer and use it in GitHub Desktop.
Save thewilsonator/654066efce91ea02e3e601bdfdd0e751 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
// foreach (Assembly b in AppDomain.CurrentDomain.GetAssemblies())
class CLRBuilder
{
static void Main(string[] args)
{
//if (args.length != 2)
// return;
string dllname = args[1]+".dll";
string outname = args[1]+".static.dll";
AppDomain ad = AppDomain.CurrentDomain;
AssemblyName iasmName = new AssemblyName();
AssemblyName oasmName = new AssemblyName();
iasmName.Name = args[1];
oasmName.Name = args[1] + "Static";
AssemblyBuilder ab = ad.DefineDynamicAssembly(
oasmName,
2/*AssemblyBuilderAccess.Save*/);
ModuleBuilder mb = ab.DefineDynamicModule(args[1]);
foreach (Type t in Assembly.Load(iasmName).GetExportedTypes())
{
TypeBuilder tb = mb.DefineType(t.Name + "Static",
TypeAttributes.Public);
foreach (MemberInfo mi in t.GetMembers())
{
if ((mi.MemberType & (MemberTypes.Method | MemberTypes.Constructor | MemberTypes.Property )) !=0)
{
addMethod(t, tb, (MethodInfo)mi);
}
}
}
ab.Save(outname);
}
static void addMethod(Type t, TypeBuilder tb, MethodInfo mi)
{
//Generate
// static mi.ReturnType mi.Name (t this, typeof(mi.GetParameters()) args...)
//{
// return this.(mi.Name)(args);
//}
List<Type> tl = new List<Type>();
tl.Insert(0,t);
tl.AddRange(mi.GetParameters().Select(p => p.ParameterType));
Type[] tps = tl.ToArray();
MethodBuilder mb = tb.DefineMethod(mi.Name,
MethodAttributes.Public |
MethodAttributes.Static,
mi.ReturnType,
tps
);
ILGenerator ilg = mb.GetILGenerator();
for (byte x = 0; x < tps.Length; x++)
{
ilg.Emit(OpCodes.Ldarg_S, x);
}
ilg.Emit(OpCodes.Callvirt, mi);
ilg.Emit(OpCodes.Ret);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment