C語言--結構體回撥函式示例
阿新 • • 發佈:2019-01-01
#include <stdio.h> struct component_provider { int component_id; const char *component_name; }; static const struct component_provider components[] = { { .component_id = 1, .component_name = "NAME-1", }, { .component_id = 2, .component_name = "NAME-2", }, { .component_id = 3, .component_name = "NAME-3", }, { .component_id = 4, .component_name = "NAME-4", }, }; int main(){ int i = 0; int max_providers = 0; const struct component_provider *providers = NULL; max_providers = sizeof(components) / sizeof(struct component_provider); providers = components; for (i = 0; i < max_providers; i++) { printf("%s\n", providers[i].component_name); } return 0; }
#include <stdio.h> struct component_obj{ void (*start_thread)(void); void (*stop_thread)(void); }; static void component_register(struct component_obj **current_obj, struct component_obj *obj) { *current_obj = obj; } //component 1 void start_sub_thread1(void){ printf("start thread 1\n"); } struct component_obj obj1 = { .start_thread = start_sub_thread1, }; //component 2 void start_sub_thread2(void) { printf("start thread 2\n"); } struct component_obj obj2= { .start_thread = start_sub_thread2, }; int main(){ struct component_obj *current_obj = NULL; component_register(¤t_obj, &obj1); current_obj->start_thread(); return 0; }
#include <stdio.h> struct component_obj{ void (*start_thread)(void); void (*stop_thread)(void); }; typedef int (*func_callback)(int c); func_callback fc=NULL; static void component_register(struct component_obj **current_obj, struct component_obj *obj) { *current_obj = obj; } //component 1 void start_sub_thread1(void){ printf("start thread 1\n"); if(!fc(1)){ printf("start thread 1 sucessfully\n"); }else { printf("start thread 1 failed! Go to rollback\n"); }; } struct component_obj obj1 = { .start_thread = start_sub_thread1, }; int main(){ struct component_obj *current_obj = NULL; component_register(¤t_obj, &obj1); int check(int num) { printf("callback, num = %d\n", num); if(num < 10){ printf("check OK\n"); } else { printf("check err\n"); return -1; } return 0; } fc=check; current_obj->start_thread(); return 0; }