Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use Reflection.Emit for the opcodes stelem.any and ldelem.any?

So, I recently did some experimenting and discovered that it appears that Reflection.Emit doesn't support all of the opcodes in the ECMA spec. There are 3 opcodes missing:

  • ldelem.any
  • stelem.any
  • no. (prefix)

Are these opcodes just not supported in the Reflection API, or is there some way to generate them or something?

like image 207
Earlz Avatar asked Nov 21 '12 16:11

Earlz


1 Answers

Actually, you can.

There is a wonderful walkthrough at http://msdn.microsoft.com/en-us/library/4xxf1410.aspx

Two essential parts are:

Create the generic parameters:

string[] typeParamNames = {"TFirst", "TSecond"};
GenericTypeParameterBuilder[] typeParams = 
    myType.DefineGenericParameters(typeParamNames);

GenericTypeParameterBuilder TFirst = typeParams[0];
GenericTypeParameterBuilder TSecond = typeParams[1];

Then create the method:

Type listOf = typeof(List<>);
Type listOfTFirst = listOf.MakeGenericType(TFirst);
Type[] mParamTypes = {TFirst.MakeArrayType()};

MethodBuilder exMethod = 
    myType.DefineMethod("ExampleMethod", 
        MethodAttributes.Public | MethodAttributes.Static, 
        listOfTFirst, 
        mParamTypes);

However, you should go through it entirely, as the generic parameters are used in so many different ways and sections (on the method, on the parameters, as result types, when invoking, ...).

-update- and if you want the .NET 2 specific version: http://msdn.microsoft.com/en-us/library/4xxf1410%28v=vs.80%29.aspx

The dropdown on the page lets you select many versions of the framework in which you can do it.

like image 53
René Wolferink Avatar answered Sep 18 '22 23:09

René Wolferink