candland

@candland rss self
April 6th 2007

Reflection.Emit.DeclareLocal and Reflection.Emit.DefineLabel

Working with Reflection.Emit today I ran into two thing that I couldn’t quickly find answers to. First, was regarding the br.s (OpCodes.Br_S) code. Secondly, was regarding an error ‘Common Language Runtime detected an invalid program’ which didn’t provide much help and the cause was not obvious. After a lot of research and trial and error I found some answers.


Regarding the first issue, I found this page on MSDN which also show’s how to create a switch statement. http://msdn2.microsoft.com/en-us/library/csx7wsz2(vs.80).aspx. The solution is to create a Label object and MakeLabel method when Emitting the IL.

Label endOfMethod = il.DefineLabel();
...
il.Emit(OpCodes.Br_S, endOfMethod);
il.MarkLabel(endOfMethod);

The above will create IL like this:

IL_0017:  br.s       IL_001
IL_0019:  ldloc.1

The second problem maybe should have been obvious, but most of what I read didn’t cover this. If you need to store something you need to create local storage before trying to store objects there. Not doing this will result in a System.InvalidProgramException. You need to create the storage with the il.DeclareLocal method passing in the Type of the object you will store there.

il.DeclareLocal(stringBuilderType);
il.DeclareLocal(typeof(string));

The above will create IL like:

.locals init (class [mscorlib]System.Text.StringBuilder V_0,
            string V_1)

Working sample command line application (.net2.0) flie – Program.cs.txt (2.45 KB)

blog comments powered by Disqus