我从这个中文博客http://chenyufei.info/blog/2011-02-28/wrap-c-function-closure-gcc-nested-function/得到这个问题 作者想在c语言中使用闭包,他发现GCC具有嵌套函数(和闭包)的能力。例如:
typedef int (*func_t)(int arg);
int foo(int a) {
return a + 1;
}
func_t create_wrap_function(func_t f) {
int wrapped(int arg) {
// call original function
int val = f(arg);
fprintf(log_func_call, "arg: %d ret: %d", arg, val);
return val;
}
return wrapped;
}
但这不是常见的解决方案。create_wrap_function 具有固定的函数格式,因为 func_t 限制了格式。
众所周知,Lua 有闭包,也可以调用 C 函数。我想实现的是:我们要调用的函数是 foo1 和 foo2,它们有不同类型的 args 和返回值。
int foo1(int a) {
...
return intValue;
}
double foo2(char* str, double a) {
...
return dblValue;
}
在 C 客户端中,调用如下函数:
lua_returnValue returnValue1 = Do_Lua_Wrap(__FILE__, __LINE__, foo1, 1);
lua_returnValue returnValue2 = Do_Lua_Wrap(__FILE__, __LINE__, foo2, "string data", 1.2345);
在 Do_Lua_Wrap 中,它将 foo1 和 1 传递给 Lua 函数,然后像正常进程一样调用 foo1 函数。然后将 foo2 和一个 char* 和一个 double 值传递给 Lua 函数,然后像正常过程一样调用 foo2 函数。在 Lua 函数中,它可以记录有关FILE和LINE的信息, 并编写一些有关函数参数的额外日志。
但是我不知道如何在 C 和 Lua 中编写函数 Do_Lua_Wrap,这可能吗?
如果可以的话,你能给我一些建议吗?