Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating IL for 2D Arrays

I want to generate IL for the 2D array construction, using System.Reflection.Emit namespace.

My C# code is

Array 2dArr  = Array.CreateInstance(typeof(int),100,100); 

Using ildasm, I realized that following IL Code is generated for the above C# code.

IL_0006:  call       class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle)
IL_000b:  ldc.i4.s   100
IL_000d:  ldc.i4.s   100
IL_000f:  call       class [mscorlib]System.Array [mscorlib]System.Array::CreateInstance(class [mscorlib]System.Type, 
                                                                                           int32,
                                                                                           int32)

I was able to generate last three IL statements as given below.

MethodInfo createArray = typeof(Array).GetMethod("CreateInstance",
                new Type[] { typeof(Type),typeof(int),typeof(int) });
gen.Emit(OpCodes.Ldc_I4_1);
           gen.Emit(OpCodes.Ldc_I4_1);
           gen.Emit(OpCodes.Call, createArray);

But I don’t have clear idea about how to generate fist IL statement (i.e. IL_0006: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) )

Do you have any idea?

Furthermore, Can somebody point put some good tutorials/documents about how to Use System.Reflection.Emit namespace in order to generate IL codes?

like image 750
Upul Bandara Avatar asked Feb 23 '23 23:02

Upul Bandara


1 Answers

Ah, good ol' typeof; yes, that is:

 il.Emit(OpCodes.Ldtoken, typeof(int));
 il.EmitCall(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle"), null);

Re guidance... my trick if I get stuck is always "compile something similar, and look at it in reflector".

If you wanted some examples, dapper-dot-net and protobuf-net both do a decent amount of IL - the first is more contained, limited and understandable; the second is all-out, no-holds-barred crazy IL.

Hints for IL:

  • track the stack in comments at EVERY step on the right hand side of the screen
  • use the short-forms of branches etc, but only use them when you know you have a very local branch
  • write yourself a little set of utility methods even for simple things like loading an integer (which is actually quite complex since there are 12 different ways of loading an int-32, depending on the value)
like image 200
Marc Gravell Avatar answered Mar 05 '23 11:03

Marc Gravell