Generating IL for 2D Arrays

爱⌒轻易说出口 提交于 2019-12-10 16:17:20

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/6260750/generating-il-for-2d-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!