Created
August 28, 2024 15:44
-
-
Save long-long-float/bf02d673a044dc3b8befb37f85958fd3 to your computer and use it in GitHub Desktop.
Get the CIL code from a compiled Regex
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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