System.Reflection.Emit fun: Find the differences
This is annoying, I am trying to make something like this works using SRE:
public void Foo(out T blah) { blah = (T)Arguments[0]; }
I created the SRE code to generate the appropriate values, but it is producing invalid code.
Works, but not verified IL:
L_0089: stloc.2
L_008a: ldarg.1
L_008b: ldloc.2
L_008c: ldc.i4 0
L_0091: ldelem.ref
L_0092: unbox.any !!T
L_0097: stobj !!T
L_009c: ret
Works, valid (csc.exe output, of course):
L_000d: stloc.1
L_000e: ldarg.1
L_000f: ldloc.1
L_0010: ldc.i4.0
L_0011: ldelem.ref
L_0012: unbox.any !!T
L_0017: stobj !!T
L_001c: ret
Comments
I don't often work down at that low of a level, but the ldloc difference stood out to me. Related to your issue, perhaps? (not that I would be in a position to say how ;)
Err, brain-fart on my part.: when I said "ldloc difference" I meant to say "ldarg versus ldloc difference across examples 1 and 2".
:)
Assuming the difference between equivalent lines L_008c and L_0010 is a typo (and ignoring that your generated code uses an extra variable), there does not seem to be any difference at all between these 2.
Can you create a valid implementation with SRE that mimics the valid example exactly (i.e. no variations in args or variables)?
Hoping you find the issue and curious as to what has caused it.
L_0010 is a shorthand version of L_008c.
According to the documentation they should behave identically.
Is there some undocumented difference?
L_008c: ldc.i4 0 <-- 4<space>0
L_0010: ldc.i4.0 <-- 4<dot>0
This is the same think.
The second is a way to specify this with one less byte/int
Maybe,
the error is in the code you don't show. In the way you defined your local variables, etc...
I played with reflection emit a lot lately (not so much with generics) and i know that finding the problems is really hard, the dreadfull Invalid program Exception is so useless...
aside from you using the 8 byte nonconstant version of ldc.i4 instead of the constant, asuming that local2 has the same type as local1 there's no difference in the two snippets. since ldc.i4 0 is not invalid that should not be the problem. If run peverify on the code what's the error message?
With SRE, it's often easy to confuse generic parameter references: when you define a generic parameter, you must always refer to that parameter using the returned GenericTypeParameterBuilder, even if you think you have found some other way to get to the same parameter. That has bitten us a few times within DynamicProxy already.
I tried, and I think I managed to get an implementation of your problem that works:
using System;
using System.Reflection.Emit;
using System.Reflection;
namespace ConsoleApplication46
{
class Program
{
}
}
Although, judging from the "!!T" in your disassembly, did you mean Foo<T>? Then it would be as follows:
var name = new AssemblyName ("MyAssembly");
Comment preview