Skip to content

Instantly share code, notes, and snippets.

@nadar71
Last active February 15, 2022 11:13
Show Gist options
  • Save nadar71/af2cc62f901a5c5421215ab68a03a8e6 to your computer and use it in GitHub Desktop.
Save nadar71/af2cc62f901a5c5421215ab68a03a8e6 to your computer and use it in GitHub Desktop.
C callback sample with parameters
/*
* 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