Note that there are some explanatory texts on larger screens.

plurals
  1. POAbout wrap and call C function
    primarykey
    data
    text
    <p>I get this question from this Chinese blog <a href="http://chenyufei.info/blog/2011-02-28/wrap-c-function-closure-gcc-nested-function/" rel="nofollow">http://chenyufei.info/blog/2011-02-28/wrap-c-function-closure-gcc-nested-function/</a> The author want to use closure in c language, and he found GCC has the ability of nested function (and closure). For example:</p> <pre><code>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; } </code></pre> <p>But it is not common solution. create_wrap_function has fixed function format, because the func_t limits the format.</p> <p>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.</p> <pre><code>int foo1(int a) { ... return intValue; } double foo2(char* str, double a) { ... return dblValue; } </code></pre> <p>In C client, call the function like:</p> <pre><code>lua_returnValue returnValue1 = Do_Lua_Wrap(__FILE__, __LINE__, foo1, 1); lua_returnValue returnValue2 = Do_Lua_Wrap(__FILE__, __LINE__, foo2, "string data", 1.2345); </code></pre> <p>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 <strong>FILE</strong> and <strong>LINE</strong> and write some extra log about function arguments.</p> <p>But I don't have idea about how to write the function Do_Lua_Wrap in C and Lua, Is it possible? </p> <p>If possible, could you give me some advices?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload