把闭包变成函数指针—— trampoline 原理解析
序 十年前,我曾经写过一个让 C 形式的回调函数支持 闭包的小转换工具, 见这。 那时候,我说过,要想把 boost.function 传给 C 接口,那这个 C 接口,必须得带一个 void* user_data 的参数。 比如 typedef int (*callback_t)(int arg1, int arg2, void* user_data); bool register_callback(callback_t cb, void* user_data); 可以利用这个 cfuntion,把 boost::function<int(int, int)> 给当成 callback_t 使用。 而 boost::function 本身又可以接受 lambda, boost::bind , 从而组合出非常易用的使用方式。 但是,这十年来,我也偶尔会遇到一些 C 库的 api , 他就只能接受裸指针,不能接受 void* user_data typedef int (*callback_t)(int arg1, int arg2); bool register_callback(callback_t cb); 这就很难受了。因为没有办法传递 void*, 也就无法给回调函数设置“上下文”。也就彻底失去了上下文关联能力了。不得不将所需的 数据通过“全局变量”传递给回调函数。十分丑陋不说,还导致回调函数变成了无法重入的。 转机 其实,如果使用 GCC 编译器,GCC 也提供一个叫 “nested function” 的功能,比如 typedef int (*callback_t)(int arg1, int arg2); bool register_callback(callback_t cb); int main() { int hello = 1; int nested_function(int arg1, int arg2) { printf("hello = %d\n", hello); } register_callback(nested_function); } 这个 nested_function 能访问 main 里定义的对象,算的上一种“闭包”了,但是,它仍然可以转换为不需要 void* 的裸函数指针。 ...