Hey,
On Mon, Aug 9, 2010 at 3:41 PM, Regis <[email protected]> wrote:
> Here is my code, but its fails to execute.
You are simply complicating things for no reason :)
Here's a slightly modified version that works just fine:
static void Main(string[] args)
{
// Create the AssemblyDefinition
AssemblyDefinition a =
AssemblyDefinition.CreateAssembly(new
AssemblyNameDefinition("TestModule", new Version()), "TestModule.dll",
ModuleKind.Dll);
AssemblyDefinition aref =
AssemblyDefinition.ReadAssembly("Assembly1.dll");
// Get the G<T> type
TypeDefinition GOfT;
GOfT = aref.MainModule.GetType("G`1");
// Get the G<T>.F static Field
FieldDefinition FinGofT;
FinGofT = GOfT.Fields[0];
// Create the Test Type
TypeDefinition Test;
a.MainModule.Types.Add(Test =
new TypeDefinition(null, "Test",
TypeAttributes.Public | TypeAttributes.Class,
a.MainModule.Import(typeof(object))));
// Create the Test.Check<U> Method
MethodDefinition CheckOfU;
Test.Methods.Add(CheckOfU = new MethodDefinition("Check",
MethodAttributes.Public | MethodAttributes.Static,
a.MainModule.Import(typeof(void))));
GenericParameter U = new GenericParameter("U", CheckOfU);
CheckOfU.GenericParameters.Add(U);
// Get the G<U> type reference
TypeReference GRef = a.MainModule.Import (GOfT);
GenericInstanceType GofU = new GenericInstanceType
(GRef);
GofU.GenericArguments.Add(U);
// Get the G<U>.F static Field
FieldReference fInGofU = new FieldReference("F", FinGofT.FieldType)
{
DeclaringType = GofU
};
// Defines the instructions
CheckOfU.Body.Variables.Add(new VariableDefinition("f",
a.MainModule.Import(typeof(int))));
CheckOfU.Body.Instructions.Add(Instruction.Create(OpCodes.Ldsfld,
fInGofU));
CheckOfU.Body.Instructions.Add(Instruction.Create(OpCodes.Stloc_0));
CheckOfU.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));
a.Write("TestModule.dll");
// Check the assembly
SR.Assembly.LoadFrom("output.dll").GetType("Test").GetMethod("Check",
SR.BindingFlags.Public |
SR.BindingFlags.Static).MakeGenericMethod(typeof
(string)).Invoke(null, null);
}
Import is no magic method you want to call every time, you need to
call it only if you're dealing with a foreign reference. Have a look
at the Import from Cecil tests to get a better understand at how you
want to do things:
http://github.com/jbevain/cecil/blob/master/Test/Mono.Cecil.Tests/ImportCecilTests.cs
--
Jb EvainĀ <[email protected]>
--
--
mono-cecil