-1

I have problem with a function pointer. I have this typedef :

typedef struct patchwork *(*create_patchwork_value_fct) 
                                            (const enum nature_primitif);

which is generic for the sake of it (implemented in another file). I want to call it with an input. How do I do ?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • This function pointer typedef works exactly the same as if you would do `typedef int* obscure_t; ...obscure_t ptr = &some_int;` – Lundin May 27 '15 at 09:38

2 Answers2

1

You need to

  1. Define a variable of the type of the typedefed function pointer.
  2. Put the address of a function having same signature to it.
  3. Use the variable as a normal function name to make the function call.

Pseudo-code

If you have a function like

struct patchwork * funccall(const enum nature_primitif)
{
  //do something
}

and then, you can do

create_patchwork_value_fct fp= funccall;
struct patchwork * retptr = NULL;
enum nature_primitif enumVal = <some enum value>;

retptr = fp(enumVal);

Maybe you can read this answer to get some more insight.

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

This isnt actually a function pointer - this is defining a function pointer type:

typedef struct patchwork *(*create_patchwork_value_fct) (const enum nature_primitif);

So, this defines a function pointer type called create_patchwork_value_fct. This is a function pointer to a function that takes a single parameter(const enum nature_primitif), and returns a struct patchwork* - i.e. a pointer to a patchwork struct.

Lets look at how this could be used:

void someFunc(create_patchwork_value_fct funcToCall, enum param)
{
    funcToCall(param);
}

struct patchwork* CreateAPatchworkValue(enum nature_primitif enumVal)
{
     struct patchwork* pwork = malloc(sizeof(struct patchwork));
     pwork->someVal = enumVal;
     return pwork;
}


void main()
{
    someFunc(CreateAPatchworkValue, <a valid nature_primitif enumeration value>)
}

in this example, main() calls someFunc(), passing it a pointer to CreateAPatchworkValue as the funcToCall parameter, and a value from the nature_primitif enum.

someFunc then calls funcToCall, which is actually a call to CreateAPatchworkValue.

mjs
  • 2,837
  • 4
  • 28
  • 48