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

1int printInt(int a){
2 
3return printf("%d",a);
4 
5}

you can define a pointer to this function as follows

1int (*funcPtr)(int);
2 
3funcPtr=printInt;

The use of the functional pointer is very similar to how we call a function

1(*funcPtr)(10);

The full program looks something like this

1#include "stdio.h"
2 
3int printInt(int a){
4 return printf("%d",a);
5}
6 
7int main(){
8 int (*funcPtr)(int);
9 funcPtr=printInt;
10 (*funcPtr)(10);
11}

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

1int printInt(int a){
2 
3return printf("%d",a);
4 
5}
6 
7void printSomething(int (*printFuncPtr)(int)){
8 
9 int a=10,b=20,c;
10 
11 c=a+b;
12 
13(*printFuncPtr)(c);
14 
15}
16 
17 
18int main(){
19 int (*funcPtr)(int);
20 funcPtr=printInt;
21 printSomething(funcPtr);
22}

You can use typedef to define the functional pointer

1#include "stdio.h"
2typedef int (*ptr)(int);
3 
4int printInt(int a){
5 return printf("%d",a);
6}
7 
8void frmtPrint(ptr ptr1){
9 (*ptr1)(2);
10}
11 
12int main(){
13 int (*funcPtr)(int);
14 funcPtr=printInt;
15 frmtPrint(funcPtr);
16}

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

1client.setCallback(callback);

here callback is function name

1void callback(char* topic, byte* payload, unsigned int length) {
2Serial.print("Message arrived [");
3Serial.print(topic);
4Serial.print("] ");
5for (int i=0;i<length;i++) {
6Serial.print((char)payload[i]);
7}
8Serial.println();
9}

The function signature should match with that of expected by the library

1#define MQTT_CALLBACK_SIGNATURE void (*callback)(char*, uint8_t*, unsigned int)

 

Add a Comment

Your email address will not be published. Required fields are marked *