关于Grand Central Dispatch中dispatch_source_handler_f系列函数参数来源的疑问
GCD中
dispatch_source_set_event_handler_f回调参数的来源 dispatch_source_set_event_handler_f的回调函数参数(void *类型)是当前的dispatch source对象本身,由系统在触发回调时自动传递。
如果你需要自定义上下文数据,可以借助GCD通用的dispatch_set_context和dispatch_get_context函数,将自定义数据与dispatch source关联:
- 创建source时,用
dispatch_set_context绑定自定义数据:
// 自定义上下文结构示例 typedef struct { int target_fd; char *read_buffer; } CustomContext; CustomContext *ctx = malloc(sizeof(CustomContext)); ctx->target_fd = your_file_descriptor; ctx->read_buffer = malloc(1024); dispatch_source_t source = dispatch_source_create(DISPATCH_TYPE_READ, ctx->target_fd, 0, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0)); dispatch_set_context(source, ctx);
- 在事件回调中,通过参数拿到source后,获取自定义上下文:
void event_handler(void *arg) { dispatch_source_t source = arg; CustomContext *ctx = dispatch_get_context(source); // 使用自定义上下文处理事件 ssize_t read_bytes = read(ctx->target_fd, ctx->read_buffer, 1024); // ...后续逻辑 } dispatch_source_set_event_handler_f(source, event_handler);
- 在取消回调中释放关联的资源:
void cancel_handler(void *arg) { dispatch_source_t source = arg; CustomContext *ctx = dispatch_get_context(source); free(ctx->read_buffer); free(ctx); // MRC环境下需释放source:dispatch_release(source); } dispatch_source_set_cancel_handler_f(source, cancel_handler);
dispatch_set_context是GCD所有对象(包括队列、源等)通用的上下文设置函数,尽管dispatch_source_create的文档未直接提及,但它是官方推荐的关联自定义数据的标准方式。
内容的提问来源于stack exchange,提问作者Daniel Walker
相关产品推荐
相关产品推荐

