Funtion pointer to a function that returns a pointer to the specified function type

To implement a state machine, I would like to achieve something like this:

currentFunction = currentFunction(int arg);

c currentFunctionis a function pointer to a function that returns a pointer to a function of the same type of function.

Is this possible in C? How?

+4
source share
3 answers

First of all, the need to really hide such things always happens due to the dirty design of the program. You are trying to solve problem X, and you think method Y will do it. So you ask us how to make Y work, although this is most likely not the right solution to start with. The root of the problem may be that X is improperly designed.

, :

typedef struct func_wrapper_t
{
  struct func_wrapper_t (*func) (int);
} func_t;

...

func_t some_function (int x)
{
  ...
  return (func_t){ some_function };
}

...

int main(void)
{
  func_t f = some_function(0);

  return 0;
}
+4

, :

typedef void( plain )( void );
typedef plain*( type )( int );

plain* Function2( int value );

plain* Function( int value )
{
    return ( plain* )&Function2 ;
}

int main( void )
{
    type* function = ( type* )Function( 55 ) ;
}

, , , , .

+1

There's an ugly solution that relies on casting

typedef void* (*FunctionType)(int);
void* func(int a){
    return (void*)func;
}

int main(void){
    FunctionType p = (FunctionType)func(3);
}
-2
source

All Articles