Implementing Interfaces
Posted: Mon Jul 06, 2009 10:55 pm
I am currently working a compiler, and would like to add support for an 'interface' construct. Anyone who has programmed C# or Java should be familiar with these. I've thought of a few ways of implementing them, and some input would be nice.
My first method involves having multiple virtual function table pointers. Each interface that the object implements would get a virtual function table pointer, and any pointer to the object typecasted as the interface would point to the virtual function table for that interface. To accomodate for the pointer offset, there would be several entry points into each function as needed that would adjust the 'this' pointer. For example:
The virtual function table pointed to by the interface pointer would point to someFunc_InterfaceEntryPoint instead of someFunc. This would also work when a class implements multiple interfaces with the same function, because you could just add another interface entry point.
The other method I have been considering involves extending the size of interface pointers. Instead of just being a pointer to the object, it would also contain a pointer to the virtual function table that implements the interface for that particular object. Function entry points would be found through the virtual function table and then called with the pointer of the object.
I am leaning towards the first method because it doesn't make every pointer twice as large, and only takes up an extra pointer in each object for each interface. Most classes that implement interfaces wouldn't have a ton of instances (for example, you probably won't have your Vector class implement interfaces) so I don't think it would waste much memory.
My first method involves having multiple virtual function table pointers. Each interface that the object implements would get a virtual function table pointer, and any pointer to the object typecasted as the interface would point to the virtual function table for that interface. To accomodate for the pointer offset, there would be several entry points into each function as needed that would adjust the 'this' pointer. For example:
Code: Select all
someFunc_InterfaceEntryPoint:
sub rcx,8
someFunc:
ret
The other method I have been considering involves extending the size of interface pointers. Instead of just being a pointer to the object, it would also contain a pointer to the virtual function table that implements the interface for that particular object. Function entry points would be found through the virtual function table and then called with the pointer of the object.
I am leaning towards the first method because it doesn't make every pointer twice as large, and only takes up an extra pointer in each object for each interface. Most classes that implement interfaces wouldn't have a ton of instances (for example, you probably won't have your Vector class implement interfaces) so I don't think it would waste much memory.