Skip to content

Instantly share code, notes, and snippets.

@theoknock
Last active October 7, 2022 20:50
Show Gist options
  • Save theoknock/b83f7eeefcdd8409c21f1ff8cdce4767 to your computer and use it in GitHub Desktop.
Save theoknock/b83f7eeefcdd8409c21f1ff8cdce4767 to your computer and use it in GitHub Desktop.
Bitwise pointer swapping. Useful for, say, a producer-consumer mutually recursive trampoline
static void(^swap_pointers)(void) =
^{
typedef typeof(unsigned long(^)(unsigned long)) predicate_function;
typedef typeof(unsigned long(^*)(unsigned long)) predicate_function_t;
predicate_function func_a, func_b;
__block void * current = (predicate_function_t)&func_a;
__block void * swap = (predicate_function_t)&func_b;
func_a = ^ unsigned long (unsigned long predicate) {
printf(" func_a returned ");
return predicate;
};
func_b = ^ unsigned long (unsigned long predicate) {
printf(" func_b returned ");
return predicate;
};
printf("Invoked current(11) and");
printf("%lu.\n", (*((predicate_function_t)(current)))(11));
printf("Swapped current with swap and then ");
(predicate_function_t)({ swap = (uintptr_t)swap ^ (uintptr_t)current ^ (uintptr_t)(current = (uintptr_t)swap); swap; });
printf("invoked current again (with a value of 24):");
printf("%lu\n", (*((predicate_function_t)(current)))(24));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment