[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: A interesting question about call C functions
- From: Greg Falcon <veloso@...>
- Date: Tue, 1 Mar 2011 17:22:23 -0500
On Mon, Feb 28, 2011 at 11:07 AM, sagasw <sagasw@gmail.com> wrote:
> Hi all,
> I get this question from this chinese
> blog http://chenyufei.info/blog/2011-02-28/wrap-c-function-closure-gcc-nested-function/
> The author want to use closure in c language, and he found GCC has the
> ability of nested function (and closure).
> For example:
>
> typedef int (*func_t)(int arg);
> func_t create_wrap_function(func_t f) {
>
> int wrapped(int arg) {
>
> // call original function
> int val = f(arg);
>
> fprintf(log_func_call, "arg: %d ret: %d", arg, val);
>
> return val;
> }
> return wrapped;
>
> }
You shouldn't do this, at least according to the GCC docs:
"If you try to call the nested function through its address after the
containing function has exited, all hell will break loose."
http://gcc.gnu.org/onlinedocs/gcc-4.5.2/gcc/Nested-Functions.html
Greg F