Function pointers are basically used in callback function, to call a particular function when a event occurs.
Callback functions are ISR(interrupt service routines) when it comes to non-os based embedded systems.
Example of using funtion pointer in C program:
---------------------
user_main.c
---------------------
*
* user_main.c
*
* Created on: 23-Feb-2016
* Author: root
*/
#include <stdio.h>
#include <user_include.h>
int main(int argc, char *argv[]){
Demo d;
d.input_string = "Jon snow";
d.print_data_pointer = data_print_1;
printer_function(&d);
d.print_data_pointer = data_print_2;
printer_function(&d);
return 0;
}
void data_print_1(char *inp){
printf("\n You Know Nothing,... %s ", inp);
}
void data_print_2(char *inp){
printf("\n You know everything, ... %s", inp);
}
void printer_function(Demo *temp){
temp->print_data_pointer(temp->input_string);
}
----------------------
user_include.h
----------------------
/*
* user_include.h
*
* Created on: 23-Feb-2016
* Author: root
*/
#ifndef USER_INCLUDE_H_
#define USER_INCLUDE_H_
/*
* typedef
*/
typedef signed char int8;
typedef unsigned char uint8;
typedef signed int int32;
typedef unsigned int uint32;
typedef struct{
void (*print_data_pointer)(char *);
char *input_string;
}Demo;
/*
* Function declaration
*/
void data_print_1(char *);
void data_print_2(char *);
void printer_function(Demo *);
#endif /* USER_INCLUDE_H_ */
Callback functions are ISR(interrupt service routines) when it comes to non-os based embedded systems.
Example of using funtion pointer in C program:
---------------------
user_main.c
---------------------
*
* user_main.c
*
* Created on: 23-Feb-2016
* Author: root
*/
#include <stdio.h>
#include <user_include.h>
int main(int argc, char *argv[]){
Demo d;
d.input_string = "Jon snow";
d.print_data_pointer = data_print_1;
printer_function(&d);
d.print_data_pointer = data_print_2;
printer_function(&d);
return 0;
}
void data_print_1(char *inp){
printf("\n You Know Nothing,... %s ", inp);
}
void data_print_2(char *inp){
printf("\n You know everything, ... %s", inp);
}
void printer_function(Demo *temp){
temp->print_data_pointer(temp->input_string);
}
----------------------
user_include.h
----------------------
/*
* user_include.h
*
* Created on: 23-Feb-2016
* Author: root
*/
#ifndef USER_INCLUDE_H_
#define USER_INCLUDE_H_
/*
* typedef
*/
typedef signed char int8;
typedef unsigned char uint8;
typedef signed int int32;
typedef unsigned int uint32;
typedef struct{
void (*print_data_pointer)(char *);
char *input_string;
}Demo;
/*
* Function declaration
*/
void data_print_1(char *);
void data_print_2(char *);
void printer_function(Demo *);
#endif /* USER_INCLUDE_H_ */
****** OUTPUT ******
You Know Nothing,... Jon snow
You know everything, ... Jon snow
No comments:
Post a Comment