Re:Ask HN: Favorite pointer tricks in C?
by aliguori on Saturday November 20, 2010 @10:44PM
(#1926230)
This isn't terribly portable FWIW. Not all calling conventions massage data into either a 32-bit or 64-bit argument. In particular, passing structs by value has some interesting rules even in the common calling conventions.
It will certainly work for 90% of the common function types out there and is a pretty common trick.
For example, if I need to call read, it's basically an invocation of a function with a 4 byte, 8 byte, and then 4 byte argument (on a 64-bit system). I have a union argument type that represents 32-bit and 64-bit parameter types at the same time. I make a call like this:
which, depending on arity of fun, invokes something like this (auto-generated): That three-arg function looks roughly like this (calling my argument type ``a_t'' to abbreviate): I generate all of the functions by arity and types and then compute an array offset of them ahead of time (so read has an offset of 5 since it returns an 8 byte value and its arguments take a 4 byte, 8 byte, and then 4 byte value).Without this trick, I'd have to use very non-portable assembler to do the same invocation (OK, I'd use libffi or dyncall's already prepackaged very non-portable assembler, which I may end up with anyway) to make this function call.