[Mono-devel-list] emitting a MethodInfo instance
Valient Gough
valient at gmail.com
Mon May 30 17:47:32 EDT 2005
I have a MethodInfo instance that I would like to emit into IL code.
Basically I need to emit a method call which takes a MethodInfo as an
argument, and the MethodInfo will be static when the IL code is
created. Is there an easy way to emit a MethodInfo instance?
The method I need to provide looks like this:
void Emit_MethodInfo( ILGenerator ig, MethodInfo method )
It looks like it could be done by emitting code which looks something
like "typeof([type]).GetMethod([name], [args])", but that is
non-trivial and is not efficient:
{
// typeof([type]).GetMethod([name], [args])
ig.Emit( OpCodes.Ldtoken, method.DeclaringType );
ig.EmitCall( OpCodes.Call, Type_GetTypeFromHandle, null );
ig.Emit( OpCodes.Ldstr, method.Name );
ParameterInfo[] parms = method.GetParameters();
Type[] parTypes = new Type[parms.Length];
for( int parN = 0; parN < parms.Length; ++parN)
parTypes[parN] = parms[parN].ParameterType;
// create an array to hold the types..
Emit_LoadInt( ig, parTypes.Length );
ig.Emit(OpCodes.Newarr, typeof(System.Type));
for(int i=0; i<parTypes.Length; ++i)
{
ig.Emit(OpCodes.Dup);
Emit_LoadInt( ig, i );
Emit_GetTypeFromHandle( ig, parTypes[i] );
ig.Emit(OpCodes.Stelem_Ref);
}
ig.Emit( OpCodes.Call,
typeof(System.Type).GetMethod("GetMethod",
new Type[] { typeof(string), typeof(Type[]) }));
}
There must be a better way?
tia,
Valient
More information about the Mono-devel-list
mailing list