# Return function pointer to a nested function in C

As the title currently mentions, I'm attempting to proclaim a nested function and also return a reminder to that function. I desire this function 'not' to return a new function reminder which will certainly return the negation of whatever the initial function was.

Below is what I have:

someType not( someType original ) {
int isNot( ListEntry* entry ) {
return !original( entry );
}

someType resultFunc = calloc( 1024, 1 );
memcpy( resultFunc, &isNot, 1024 );

return resultFunc;
}


someType is specified as:

typedef int(*someType)(ListEntry* entry)

1
2022-06-07 14:30:47
Source Share

I'm making use of GCC.

You can activate nested features by utilizing the flag:

-fnested-functions


when you compile.

0
2022-06-07 14:46:00
Source

Steve, you have an entirely incorrect psychological version of what is a C function.

someType resultFunc = calloc( 1024, 1 );
memcpy( resultFunc, &isNot, 1024 );


From your code piece, I can theorize that you assume that you can replicate function is assembled code right into a block of memory, and afterwards recycle it. This example gives off Lisp, other than also in lisp you do not do it in this way.

Actually, when you claim "&isNot", you get a reminder to function. Duplicating the memory that reminder factors at is disadvantageous - the memory was booted up when you filled your executable right into memory, and also it is not transforming. Regardless, creating someFunc() would certainly create a core dump, as the lot memory behing someFunc can not be implemented - this shields you from all type of infections.

You appear to anticipate an execution of closures in C. That execution is merely not there. Unlike Lisp or Perl or Ruby, C can not maintain components of a pile structure as soon as you left that structure. Also is nested features are allowed in some compilers, I make certain that you can not describe non - international variables from inside those features. The closes point to closures is without a doubt C+npls object that shops the state and also applies operator(), yet it is an entirely various strategy, and also you would certainly still need to do points by hand.

Update: here is the pertinent section of GCC documents. Seek "But this strategy functions just as long as the having function (hack, in this instance) does not exit."

19
2022-06-07 14:44:28
Source

I additionally never ever come across nested features in C, yet if gcc sustains it, this is not mosting likely to function the means you anticipate. You are just merely replicating the equipment guidelines of isNot, which will not include the real value of "original" at the time "not" is being called.

You need to make use of a C+npls class to implement a function object that saves a reminder that you can boot up with the value of "original" and also return an instance of this class from "not".

0
2022-06-07 14:44:07
Source