mardi 14 janvier 2020

Getting value from top of IL stack using IL Emit

I have a LocalBuilder, which is essentially an array. I can use it in IL just fine, and I can load it's length using OpCodes.Ldlen. I was just wondering, if there is any way to get the length from top of stack to some actual variable. I am looking for something like

int lengthVariable = 0;

IL.Emit(OpCodes.Ldloc, arr);
IL.Emit(OpCodes.Ldlen);
IL.Emit(??????, lengthVariable);

I want to get this variable so that I can run a loop based on array's length. I know I can create a loop in IL, but I thought it would be a lot more convenient if this was possible.

Edit: What I'm trying to do over here is

  • Call an external method (which returns array).
  • Perform some action on all the elements of that array. Currently, I am doing this by having two copies of of array (IL and non-IL). Using the non-IL copy, I get the length, and then perform the action n number of times.

The problem with this is that I now have to call the external method twice. I was hoping that I could get the length from IL array so that I can loop over it directly, without calling the external method twice. I know I can write a for loop in IL, but I was kind of avoiding writing branching statements of IL.





Aucun commentaire:

Enregistrer un commentaire