Question

I'm trying to generate dynamic method. Assume I have bool value arg in stack. I want to call a method that accepts argument of type int that will be converted from that bool value by simple rule arg ? 1 : 0. For some sample code generated IL code is below:

//bool value is already pushed into stack
IL_003d:  brtrue.s  IL_0042
IL_003f:  ldc.i4.0
IL_0040:  br.s      IL_0043
IL_0042:  ldc.i4.1
IL_0043:  callvirt --methodName--

When emmiting OpCodes.Brtrue_S and OpCodes.Br_S how can I correctly identify offset to jump to?

Was it helpful?

Solution

If you really just want to convert true to 1 and false to 0, you can use the fact that types smaller than 4 bytes are expanded to 4 bytes on the stack. This means you don't have to do anything and just treat the bool as an int.

If you actually want a ternary operator, you can use the pair of methods DefineLabel() and MarkLabel():

var trueLabel = il.DefineLabel();
var endLabel = il.DefineLabel();

il.Emit(OpCodes.Brtrue, trueLabel);

il.Emit(OpCodes.Ldc_I4_0);

il.Emit(OpCodes.Br, endLabel);

il.MarkLabel(trueLabel);

il.Emit(OpCodes.Ldc_I4_1);

il.MarkLabel(endLabel);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top