Guest User

Mono.Cecil experiment

a guest
Mar 24th, 2010
386
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.28 KB | None | 0 0
  1. using System;
  2. using System.Linq;
  3. using System.Reflection;
  4. using Mono.Cecil;
  5.  
  6. namespace CecilTest
  7. {
  8.     public interface MyInterface<T>
  9.     {
  10.         T InterfaceMethod();
  11.     }
  12.  
  13.     public class MyClass : MyInterface<string>
  14.     {
  15.         public string InterfaceMethod()
  16.         {
  17.             return "MyClass.InterfaceMethod()";
  18.         }
  19.     }
  20.  
  21.     class Program
  22.     {
  23.         static void Main(string[] args)
  24.         {
  25.             Console.WriteLine(new MyClass().InterfaceMethod());
  26.  
  27.             var inputAssemblyPath = Assembly.GetEntryAssembly().Location;
  28.             var entryAssembly = AssemblyFactory.GetAssembly(inputAssemblyPath);
  29.             var mainModule = entryAssembly.Modules.Cast<ModuleDefinition>().First();
  30.             var types = mainModule.Types;
  31.  
  32.             var MyInterfaceT = types[1];
  33.             var MyInterfaceTMethod = MyInterfaceT.Methods[0];
  34.             var MyInterfaceString = types[2].Interfaces[0];
  35.  
  36.             // According to you:
  37.             var MyInterfaceStringMethod = MakeGeneric(MyInterfaceTMethod, MyInterfaceString);
  38.             Console.WriteLine(MyInterfaceStringMethod.MetadataToken);  // this outputs Module [0x0000], which looks wrong
  39.  
  40.             // Try to set the method override to MyInterfaceStringMethod
  41.             types[2].Methods[0].Overrides.Add(MyInterfaceStringMethod);
  42.             AssemblyFactory.SaveAssembly(entryAssembly, @"C:\temp\output.exe");  // change the path as needed
  43.  
  44.             // Now open output.exe in ildasm and look at MyClass.InterfaceMethod(). It'll say:
  45.             //
  46.             //     .override 'INVALID TOKEN: 0x06000000'
  47.             //
  48.             // Observe that it's now Method [0x0000]...
  49.             // The correct token would have been MemberRef [0x0001], although I don't know why
  50.         }
  51.  
  52.         static MethodReference MakeGeneric(MethodReference method, TypeReference declaringType)
  53.         {
  54.             var reference = new MethodReference(method.Name, declaringType, method.ReturnType.ReturnType, method.HasThis, method.ExplicitThis, MethodCallingConvention.Generic);
  55.             foreach (ParameterDefinition parameter in method.Parameters)
  56.                 reference.Parameters.Add(new ParameterDefinition(parameter.ParameterType));
  57.             return reference;
  58.         }
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment