lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hi all,

I get this question from this chinese blog http://chenyufei.info/blog/2011-02-28/wrap-c-function-closure-gcc-nested-function/
The author want to use closure in c language, and he found GCC has the ability of nested function (and closure).
For example:
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;
}

But it is not common solution. create_wrap_function has fixed function format, because the func_t limits the format.

As we know, Lua has closure, and could call C function too.
What I want to implement like:
The functions we want to call is foo1 and foo2, they has different types of args and return value.
int foo1(int a) {
    ...
return intValue;
}


double foo2(char* str, double a) {
...
return dblValue;
}

In C client, call the function like:
    lua_returnValue returnValue1 = Do_Lua_Wrap(__FILE__, __LINE__, foo1, 1);
    lua_returnValue returnValue2 = Do_Lua_Wrap(__FILE__, __LINE__, foo2, "string data", 1.2345);

In the Do_Lua_Wrap, it will pass the foo1 and 1 to the Lua function, then call foo1 function like normal process.
Then pass the foo2 and one char* and one double value to the Lua function, then call foo2 function like normal process.
In the Lua function, it could log the information about __FILE__ and __LINE__ 
and write some extra log about function arguments.

But I don't have idea about how to write the function Do_Lua_Wrap in C and Lua, 
Is it possible? 
If possible, could you give me some advices?

Many thanks,

sagasw

------------------------------------------
blog: http://sunxiunan.com/
C++, Lua, living in Dalian
http://twitter.com/sagasw
------------------------------------------