[Mono-list] Obtaining a generic MonoMethod

Robert Jordan robertj at gmx.net
Mon Dec 4 04:08:50 EST 2006


Andreas Färber wrote:
> Hi Robert,
> 
>>> I would like to invoke the generic method IList<T>.Add(T) on an
>>> object - how can I do this?
>>>
>>> I've been able to get a MonoClass of "IList`1" but neither using
>>> mono_class_get_method_from_name nor using a MonoMethodDesc did I
>>> succeed in retrieving a non-zero MonoMethod*.
>> Unlike System.Collections.IList, System.Collections.IList`1
>> doesn't define the member "Add". ICollection`1 does it.
> 
> Sorry, must have mixed up the doc pages then.
> 
> Still, obtaining a non-zero ICollection`1 MonoClass*, I get a non- 
> zero mono_class_get_method_from_name(cls, "Add", 1) MonoMethod*  
> ("System.Collections.Generic.ICollection`1:Add (T)") - but then if I  
> do mono_object_get_virtual_method, mono_method_full_name on the  
> returned MonoMethod* says it's System.Object:Finalize()!
> (I personally consider this a bug 'cause if I'm doing something wrong  
> I would expect a NULL MonoMethod* instead of a pointer to a method I  
> didn't request! Should I file a bug report?)
> 
> So please consider it a general question: How do I correctly invoke a  
> generic method? ;-)

You call methods of generic classes like every other method.
The "trick" is to get the method from the "inflated" class,
which you can obtain from mono_object_get_class ().

MonoClass *clazz = mono_object_get_class (obj);

/*
  * untested. If there are more Add methods declared, you
  * may use mono_method_desc_search_in_class (clazz, ":Add(T)")
  */
MonoMethod *method = mono_class_get_method_from_name (clazz, "Add", 1);

mono_runtime_invoke (method, obj, args, &exception);

Robert



More information about the Mono-list mailing list