置頂
nested-function
小弟在C上遇到一個關於nested-function的疑惑想請教
以下是jserv大在他的網頁中提到的一份sample code
typedef int (*func_t)(int);
static func_t(int arg) {
int nested(int nested_arg) {
return (arg + nested_arg);
}
return &nested;
}
int main()
{
{
func_t = f(0x1ab);
printf("%d\n", (*g)(20));
}
printf("%d\n", f(400)(27));
printf("%d\n", f(f(400)(27))(20));
return 0;
}
這樣單純傳value的nested-function是沒有問題的
小弟依樣畫葫蘆,做了一個傳function的版本,以下是小弟自己的code
typedef void (*ret_func)(void);
typedef void (*work_func)(void *data);
void show_a(void *data)
{
printf("This is show_a function\n");
}
void show_b(void *data)
{
printf("This is show_b function\n");
}
ret_func func_gen(work_func func)
{
void inside_func(void) {
printf("-\n");
(*func)(NULL);
printf("-\n");
}
return &inside_func;
}
int main()
{
ret_func ptr;
ptr = func_gen(&show_a);
(*ptr)();
return 0;
}
以上是小弟的sample,不過卻會直接的Segmentation fault
小弟想做的其實是動態將function再額外用另一個interface包起來
目的是不想讓更外層的人去使用到底層的interface,所以才想說用這種方式
不過並不是很清楚死掉的原因,還請先進給予指點
會員登入
(先登入會員才能回覆留言喔!)
