2

I am implementing callback functions in this way:

typedef void (*callback)()

Its works fine and i can pass arguments to such callbacks:

void Call(int X){
   printf("Input: %d", X);
}
void PrintSomething(callback F){
   printf("Something");
   F(10);
}

But i can not shake the feeling that I am doing something wrong. Is my method memory safe ? Is any other good method for implementing callbackfunctions with parrameters ?

user3640470
  • 121
  • 1
  • 3
  • You need to define the type of the parameters `typedef void (*callback)(int)` – z̫͋ May 15 '14 at 11:49
  • Function pointers are valid part of C language. But I suggest at least check if it's non void before calling. See this answer for more details: http://stackoverflow.com/questions/142789/what-is-a-callback-in-c-and-how-are-they-implemented – KBart May 15 '14 at 11:50

2 Answers2

1

It is safe as long as you somehow make sure the actual arguments match the function signature. If you want the compiler to check it for you, you need to define a separate callback type for each signature:

typedef void (*callback_ii)(int, int);
typedef void (*callback_d)(double);
typedef void (*callback_v)(void);

This is no different from regular function declarations. You can declare your function in a header file like this:

void PrintSomething();

but then you are on your own with the signature checking.

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243
1

I don't think code you have given will compile as callback is function pointer which returns void and takes no parameter but in PrintSomething argument 10 is passed to F.

Coming to the question then callback implementation is done in the right way there is no wrong. You declare a signature to your callback function like return values, parameters and other attributes and then register the client's callback and call.

Its how POSIX thread and other thread libraries do.

Thanks

user3494614
  • 603
  • 1
  • 7
  • 20
  • 1
    Declaring a function without argument, does **not** mean it does not take arguments, but that any number of arguments may be passed. To declare a function with definitly no arguments returning nothing do it this way: `void function_with_defintily_no_arguments(void);` – alk May 15 '14 at 12:02
  • This answer would be correct for C++. – molbdnilo May 16 '14 at 12:48