Vtables in C
- Virtual Table
- Vtable
- In ANSI C, is either an array or a structure containing function pointers.
- Function Pointer
- In ANSI C, a function pointer represents the address of a block of code in memory. This allows the programmer to pass around existing functions as parameters to other functions.
There are two use cases that come to mind for me when it comes to vtables:
- Module Namespaces, and,
- Object-Oriented Programming
This one is pretty simple, one defines a library of
functions but doesn't want to clutter up the global
namespace of your library consumers' code. The normal
way to go about this is to prepend the library
functions with the library name and an underscore,
like "mylib_function
" and so on.
Frankly, this to me looks a bit messy. And to add insult to injury, most autocomplete frameworks handle this pretty badly in that it matches against the entire name, which ends up giving you both function, variable and macro names when all you wanted were functions. Even intelligent completion frameworks like the ones used for LSPs handle this bandly, often defaulting to the former string search.
On the other hand, support for struct property completion is pretty good across the board. Since we add function pointers to a struct in a vtable, we are able to take advantage of this for organizing our library code. You only export a few variables of your vtable type, and library users would use the properties within that variable to interface with your code.
Suppose we have a struct and a collection of functions that operate on that struct. We can include a pointer to the vtable type in the struct definition to easily discover what "methods" it has. Alas, there isn't any easy way of passing the implicit self parameter to these functions.