Last active
February 15, 2022 11:13
-
-
Save nadar71/af2cc62f901a5c5421215ab68a03a8e6 to your computer and use it in GitHub Desktop.
C callback sample with parameters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* This is a simple C program to demonstrate the usage of callbacks | |
* The callback function is in the same file as the calling code. | |
* The callback function can later be put into external library like | |
* e.g. a shared object to increase flexibility. | |
* | |
*/ | |
#include <stdio.h> | |
#include <string.h> | |
typedef struct _MyMsg{ | |
int appId; | |
char msgbody[32]; | |
} MyMsg; | |
void myfunc(MyMsg *msg) | |
{ | |
if (strlen(msg->msgbody) > 0 ) | |
printf("App Id = %d \nMsg = %s \n",msg->appId, msg->msgbody); | |
else | |
printf("App Id = %d \nMsg = No Msg\n",msg->appId); | |
} | |
/* | |
* Prototype declaration | |
*/ | |
void (*callback)(MyMsg *); | |
int main(void) | |
{ | |
// define the parameter | |
MyMsg msg1; | |
msg1.appId = 100; | |
strcpy(msg1.msgbody, "This is a test\n"); | |
/* | |
* Assign the address of the function "myfunc" to the function | |
* pointer "callback" (may be also written as "callback = &myfunc;") | |
*/ | |
callback = myfunc; | |
/* | |
* Call the function (may be also written as "(*callback)(&msg1);") | |
*/ | |
callback(&msg1); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment