以下代码不能按预期工作,但希望说明我的尝试:
long foo (int a, int b) {
return a + b;
}
void call_foo_from_stack (void) {
/* reserve space on the stack to store foo's code */
char code[sizeof(*foo)];
/* have a pointer to the beginning of the code */
long (*fooptr)(int, int) = (long (*)(int, int)) code;
/* copy foo's code to the stack */
memcpy(code, foo, sizeof(*foo));
/* execute foo from the stack */
fooptr(3, 5);
}
Run Code Online (Sandbox Code Playgroud)
显然,sizeof(*foo)不返回foo()函数代码的大小.
我知道在某些CPU上执行堆栈是受限制的(或者至少在设置了限制标志的情况下).除了最终可以存储在堆栈中的GCC嵌套函数之外,还有一种方法可以在标准C中实现吗?