[Mono-list] Re: [Mono-devel-list] Technical questions

Jonathan Pryor jonpryor@vt.edu
Tue, 19 Aug 2003 20:58:06 -0400

You should ask this on mono-list, so I'm ccing them, but I believe
mono's virtual method implementation is reminiscent of C++ virtual
function tables.

Each object instance (a subclass of MonoObject; see "object.h") contains
a pointer to a virtual function table.  Strictly speaking, it contains a
pointer to a MonoVTable instance (the MonoObject::vtable field; see
"class.h"), which contains the virtual function table
(MonoVTable::vtable), along with other important information (the
runtime class -- MonoVTable::class; implemented interfaces --
MonoVTable::interface_offsets; etc.).

You might also want to look into how GObject (in glib) is implemented. 
Many mono developers are also Gnome/GTK developers, and they used the
same basic "OO in C" principals when implementing mono.

Each virtual function has a "slot" index associated.  It doesn't matter
how the index is computed, as long as it's unique for a given method
signature.  It must be unique for the signature, so that overriding
methods get the same slot index (allowing the derived-implementation to
be invoked through pointers to the base class).  For example:

	public class System.Object {
		public virtual bool Equals (object other);
		public virtual string ToString ();
		// ...

For the above class, Equals() could have the slot 0 and ToString() could
have the slot 1.

So, when you need to invoke a virtual function, you get the virtual
function table, get the index for the function to call, and invoke it.

	// just to convey the basic idea...
	MonoObject *o = get_my_object(...);
	void** params = get_my_method_params (...);
	int idx = get_method_index (...);
	MonoMethod *m = o->vtable->klass->vtable[idx];
	MonoObject* exception = NULL;
	mono_runtime_invoke (m, o, params, &exception);
	// ...

The big questions are:
 1. How is the the index found/generated?
 2. How is the MonoMethod *really* found.  I suppose it could just be a 
    direct array access, as I did above, and it looks to be the case 
    (see gc.c, with:
	mono_runtime_invoke (o->vtable->klass->vtable [finalize_slot], 
	o, NULL, &exc); 
    ) but there are other ways it could be done as well.

 - Jon

On Tue, 2003-08-19 at 20:05, Chris Seaton wrote:
> I've having trouble understanding how virtual methods work (the
> implementation, I mean - I get the theory). Looking at the source isn't
> helping. In Mono, does every instance of a type carry details of that
> type (sort of as a field)? That's the only way I could think that it
> would be able to select the correct method. If so, does this even apply
> to structure types and the fundamentals such as int and bool?