diff --git a/src/ComputeSharp.Shaders/Extensions/DynamicMethod{T}.cs b/src/ComputeSharp.Shaders/Extensions/DynamicMethod{T}.cs new file mode 100644 index 00000000..5185d2ec --- /dev/null +++ b/src/ComputeSharp.Shaders/Extensions/DynamicMethod{T}.cs @@ -0,0 +1,62 @@ +using System; +using System.Diagnostics.Contracts; +using System.Linq; +using System.Reflection; +using System.Reflection.Emit; +using System.Threading; + +namespace ComputeSharp.Shaders.Extensions +{ + /// + /// A that can be used to easily (lol) create dynamic methods + /// + /// The type of that will be used to wrap the new methods + public static class DynamicMethod where T : Delegate + { + /// + /// The return type of the + /// + private static readonly Type ReturnType; + + /// + /// The array of types of the arguments of the + /// + private static readonly Type[] ParameterTypes; + + /// + /// Loads all the necessary info for the current parameter + /// + static DynamicMethod() + { + MethodInfo method = typeof(T).GetMethod("Invoke"); + ReturnType = method.ReturnType; + ParameterTypes = method.GetParameters().Select(p => p.ParameterType).ToArray(); + } + + /// + /// Local counter for dynamic methods of type ever generated + /// + private static int _Count; + + /// + /// Creates a new for the target owner + /// + /// The instance that will own the new method + /// An that builds the IL bytecode for the new method + /// A new dynamic method wrapped as a + [Pure] + public static T New(Type owner, Action builder) + { + // Create a new dynamic method with a unique id + string id = $"__IL__{typeof(T).Name}_{Interlocked.Increment(ref _Count)}"; + DynamicMethod method = new DynamicMethod(id, ReturnType, ParameterTypes, owner); + + // Build the IL bytecode + ILGenerator il = method.GetILGenerator(); + builder(il); + + // Build and delegate instance + return (T)method.CreateDelegate(typeof(T)); + } + } +}