Functional pointers in C
|C supports pointers to functions. Functions are not variables but you can define a pointer to a function. The function name refers to the address of the function much like array name points to first element.
lets define a function , this function takes a integer as parameter and prints it
int printInt(int a){ return printf("%d",a); }
you can define a pointer to this function as follows
int (*funcPtr)(int); funcPtr=printInt;
The use of the functional pointer is very similar to how we call a function
(*funcPtr)(10);
The full program looks something like this
#include "stdio.h" int printInt(int a){ return printf("%d",a); } int main(){ int (*funcPtr)(int); funcPtr=printInt; (*funcPtr)(10); }
We can also pass the functional pointers to other functions.Continuing with the previous example , let us assume that there is method which expects a functional pointer as a parameter to print its output
int printInt(int a){ return printf("%d",a); } void printSomething(int (*printFuncPtr)(int)){ int a=10,b=20,c; c=a+b; (*printFuncPtr)(c); } int main(){ int (*funcPtr)(int); funcPtr=printInt; printSomething(funcPtr); }
You can use typedef to define the functional pointer
#include "stdio.h" typedef int (*ptr)(int); int printInt(int a){ return printf("%d",a); } void frmtPrint(ptr ptr1){ (*ptr1)(2); } int main(){ int (*funcPtr)(int); funcPtr=printInt; frmtPrint(funcPtr); }
Lets a real world example where we use functional pointers.
MQTT is publish/subscribe based messaging protocol. PubSubClient is one of the library available for arduino.
To receive messages from broker , you need a set a callback function, So your code will be invoked by the library when there is new message on the subscribed channels. The following snippet is from PubSubClinet example mqtt_basic
client.setCallback(callback);
here callback is function name
void callback(char* topic, byte* payload, unsigned int length) { Serial.print("Message arrived ["); Serial.print(topic); Serial.print("] "); for (int i=0;i<length;i++) { Serial.print((char)payload[i]); } Serial.println(); }
The function signature should match with that of expected by the library
#define MQTT_CALLBACK_SIGNATURE void (*callback)(char*, uint8_t*, unsigned int)