Thunk

Thunks are primarily used to delay a calculation until its result is needed, or to insert operations at the beginning or end of the other subroutine.

It refers to the original use of thunks in ALGOL 60 compilers, which required special analysis (thought) to determine what type of routine to generate.

A key question was how to compile a subroutine call if the arguments can be arbitrary mathematical expressions rather than constants.

Peter Ingerman first described thunks in reference to the ALGOL 60 programming language, which supports call-by-name evaluation.

[4] Although the software industry largely standardized on call-by-value and call-by-reference evaluation,[5] active study of call-by-name continued in the functional programming community.

[8] As a direct approach to this pointer adjustment problem, the compiler can include an integer offset in each dispatch table entry.

The solution just described has problems similar to the naïve implementation of call-by-name described earlier: the compiler generates several copies of code to calculate an argument (the instance address), while also increasing the dispatch table sizes to hold the offsets.

As an alternative, the compiler can generate an adjustor thunk along with C's implementation of Access that adjusts the instance address by the required amount and then calls the method.

A compiler (or other tool) can solve this problem by generating a thunk that automates the additional steps needed to call the target routine, whether that is transforming arguments, copying them to another location, or switching the CPU mode.

Much of the literature on interoperability thunks relates to various Wintel platforms, including MS-DOS, OS/2,[10] Windows[11][12][13][14] and .NET, and to the transition from 16-bit to 32-bit memory addressing.