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?
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With