0%

GCC extension: Nested function in C

在CodeProject看到這篇文章之後,參考其他文章而發表的。

GCC nested function

這個Extension只支援GNU C,Clang或者VC++都不行。
這種技術有其名稱,叫做trampoline

這個Hack可模擬Javasciprt等語言使用Closure的特性

lang: c
1
2
3
4
5
6
7
8
typedef int (*func_t)(int);
static func_t f(int arg) {
int nested(int nested_arg) {
return (arg + nested_arg);
}
return &nested;
}

原文提供了更變態的使用方式,不過很難閱讀。

lang: c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main(int argc, char *argv[]) {
void (*MySub1)() = ({void _() {
printf("Hello ");
} (void (*)())_;});

MySub1();

({void _() {
printf("World!\n");
} (void (*)())_;})();

return 0;
}

原理