1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
| typedef struct callback_node { void *func_ptr; void *user_data; char func_signature[64]; struct callback_node *next; } callback_node_t;
typedef struct callback_manager { callback_node_t *callbacks; pthread_mutex_t mutex; size_t callback_count; } callback_manager_t;
callback_manager_t* callback_manager_create() { callback_manager_t *manager = calloc(1, sizeof(callback_manager_t)); if (!manager) return NULL; pthread_mutex_init(&manager->mutex, NULL); return manager; }
#define REGISTER_CALLBACK(manager, func, signature, data) \ register_callback_internal(manager, (void*)(func), signature, data, \ sizeof(signature) - 1)
int register_callback_internal(callback_manager_t *manager, void *func_ptr, const char *signature, void *user_data, size_t sig_len) { if (!manager || !func_ptr) return -1; callback_node_t *node = calloc(1, sizeof(callback_node_t)); if (!node) return -1; node->func_ptr = func_ptr; node->user_data = user_data; strncpy(node->func_signature, signature, sizeof(node->func_signature) - 1); node->func_signature[sizeof(node->func_signature) - 1] = '\0'; pthread_mutex_lock(&manager->mutex); node->next = manager->callbacks; manager->callbacks = node; manager->callback_count++; pthread_mutex_unlock(&manager->mutex); return 0; }
#define INVOKE_CALLBACKS(manager, signature, ...) \ invoke_callbacks_internal(manager, signature, ##__VA_ARGS__)
void invoke_callbacks_internal(callback_manager_t *manager, const char *signature, ...) { if (!manager) return; pthread_mutex_lock(&manager->mutex); callback_node_t *current = manager->callbacks; while (current) { if (strcmp(current->func_signature, signature) == 0) { if (strcmp(signature, "void(*)(int,void*)") == 0) { va_list args; va_start(args, signature); int param = va_arg(args, int); va_end(args); void (*callback)(int, void*) = current->func_ptr; callback(param, current->user_data); } } current = current->next; } pthread_mutex_unlock(&manager->mutex); }
|