What is a `thunk`?

A thunk is a piece of code that deals with an impedance mismatch between caller and callee.

Perhaps an example from the Windows world might be easier to understand:

As Windows evolved from 16 bit -> 32 bit -> 64 bit, it was necessary for new code to call older code, and in some circumstances, the reverse.

Take an app written for Windows 3.1. It would run unmodified on Windows 95, even though some of the system APIs were written as 32-bit code. How does the 16-bit code, which is passing 16-bit wide words, call the new 32-bit code? The answer is that MS introduced thunks for the 16-bit entry points which widened the parameters before calling the new 32-bit implementation and then narrowed the return type to 16-bits, if necessary.

14 Likes