Wikipedia / Dispatch table
Wikipedia / Dispatch table
In computer science, a dispatch table is a data structure that maps a series of known actions to their corresponding code, which can later be retrieved dynamically. This structure is commonly implemented either using an associative array to directly map method names to a corresponding function pointer, or a simple array of function pointers with known indices.
Common use cases include the implementation of late binding and virtual polymorphism in object-oriented programming and the implementation of system calls.
Use cases
Virtual methods
In object-oriented programming languages that support virtual methods, the compiler will automatically create a dispatch table for each class that maps method names to their corresponding code. This table is called a virtual method table or vtable, and a pointer to the table is stored in every object created from that class, called a virtual pointer or vptr. Since an object always has direct access to its methods using the vptr, virtual methods can be dynamically called at runtime without needing to know the specific class that the object is constructed from. This layer of indirection makes polymorphism and late binding possible, which is a fundamental aspect of object-oriented programming.
System calls
In operating system kernel design, system calls are commonly implemented using a dispatch table of indices mapping to corresponding privileged system actions. For example, in Linux, the sys_exit system call has an index of 60, and can be called by passing 60 into the appropriate processor register and triggering a program interrupt.Since system calls only require a number to reference the underlying kernel action, they can be called from user space while in reality triggering code in kernel space. This improves system security by ensuring that privileged code can only be run through the narrow interface that each call provides.
Example implementations
Perl
The following shows one way to implement a dispatch table in Perl, using a hash to store code references (also known as function pointers).
Running this Perl program as perl greet -h will produce "hello", and running it as perl greet -g will produce "goodbye".
JavaScript
A dispatch table can be implemented in JavaScript by using an object to store anonymous function definitions.
Lua
In Lua, tables can store any value, including functions, making it trivial to implement a simple dispatch table.
See also
References
Diomidis Spinellis (2003). Code Reading: The Open Source Perspective. Boston, MA: Addison-Wesley.