次の方法で共有


Try ILReader

 # 
# Sample code to demonstrate how to use ILReader
# By Haibo Luo @ https://blogs.msdn.com/haibo_luo
#
# THIS CODE IS PROVIDED "AS IS", WITH NO WARRANTIES INTENDED OR IMPLIED. USE AT YOUR OWN RISK
#

import clr, sys, System
try:
    clr.AddReference(r'ClrTest.Reflection.ILReader.dll')
except: 
    print '\nFail to add reference of ILReader. One simple fix is to copy ILReader.dll to the current directory.'
    sys.exit(1)
    
from ClrTest.Reflection import *

# 
# Find which method could throw the specified exception
# 
class ThrowExceptionHunter(ILInstructionVisitor):
    def __init__(self, method, exceptionType): 
        self.method = method
        self.ctors = exceptionType.GetConstructors()
        self.found = False
    def VisitInlineMethodInstruction(self, instruction): 
        if instruction.Method in self.ctors:
            print instruction.Method, '|', self.method
            self.found = True

clrStringType = clr.GetClrType(System.String)
exceptionType = clr.GetClrType(System.ArgumentOutOfRangeException)
for method in clrStringType.GetMethods():
    h = ThrowExceptionHunter(method, exceptionType)
    for il in ILReader(method): 
        il.Accept(h)
        if h.found: break

# 
# Find all methods called by String.StartsWith
# 
method = clrStringType.GetMethod('StartsWith', System.Array[System.Type]([str, System.StringComparison]))
reader = ILReader(method)

class CalleeFinder(ILInstructionVisitor):
    def __init__(self):
        self.callees = []
    def VisitInlineMethodInstruction(self, instruction): 
        self.callees.append(instruction.Method)

v = CalleeFinder()
reader.Accept(v)
print "How many:", len(v.callees)
for x in v.callees: 
    print x, '/', x.DeclaringType

# 
# Find all unique methods called by String.StartsWith
# 
class CalleeFinderNoDup(ILInstructionVisitor):
    def __init__(self):
        self.callees = set()
    def VisitInlineMethodInstruction(self, instruction): 
        self.callees.add(instruction.Method)

v = CalleeFinderNoDup()
reader.Accept(v)
print "How many:", len(v.callees)
for x in v.callees: 
    print x, '/', x.DeclaringType

# 
# print the IL for String.StartsWith 
# 
v = ReadableILStringVisitor(ReadableILStringToTextWriter(System.Console.Out))
reader.Accept(v)

Comments

  • Anonymous
    November 06, 2006
    Compared to what I posted previously here (or what was used in the DynamicMethod visualizer ), this new

  • Anonymous
    September 13, 2007
    Has anyone seen a recent version of Lutz Roeder's ILReader?  The only version I've found floating about supports an old assembly version and I need to do analysis on newer, .NET 2.0 assemblies.