Hacker News new | ask | show | jobs
by gok 2980 days ago
So how are function pointers in (say) C implemented?
2 comments

From playing around with https://mbebenita.github.io/WasmExplorer/ : it seems like any function you ever take the address of gets stored in the table, and wasm just passes the index in that table around. And if you do things like cast an integer to a function pointer, you actually just cast it to an index in the table.

C is high-level enough that IIRC it doesn't guarantee that arbitrary addresses can successfully be used as function pointers; the only valid function pointers are results of addresses of functions, or (possibly) values that have been cast from and then to them. Which is enough for wasm.

Try compiling this (to wat, which is an S-expression format that otherwise resembles the assembly in this article): https://wasdk.github.io/WasmFiddle/?5zbjb

In C, a function pointer is typically just the address of the first assembly instruction in that function. Invocation is typically done by an instruction that does a subroutine call to that address stored in a register.