Skip to content

Instantly share code, notes, and snippets.

@long-long-float
Created August 28, 2024 15:44
Show Gist options
  • Save long-long-float/bf02d673a044dc3b8befb37f85958fd3 to your computer and use it in GitHub Desktop.
Save long-long-float/bf02d673a044dc3b8befb37f85958fd3 to your computer and use it in GitHub Desktop.
Get the CIL code from a compiled Regex
using System;
using System.Reflection.Emit;
using System.Reflection;
using System.Text.RegularExpressions;
namespace RegexCil
{
internal class Program
{
private delegate void NoParamDelegate(RegexRunner r);
private static void Main(string[] args)
{
Regex regex = new Regex(@".*\. ", RegexOptions.Compiled);
var factory = typeof(Regex).GetField("factory", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(regex) as RegexRunnerFactory;
var goMethod = factory.GetType().GetField("goMethod", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(factory) as DynamicMethod;
var goDele = goMethod.CreateDelegate(typeof(NoParamDelegate));
var ilGen = goMethod.GetILGenerator();
MethodInfo dynMethod = typeof(ILGenerator).GetMethod("BakeByteArray", BindingFlags.NonPublic | BindingFlags.Instance);
var code = dynMethod.Invoke(ilGen, []) as byte[];
Console.WriteLine(BitConverter.ToString(code).Replace("-", " "));
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment