我从这个博客中国这个问题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;
}
Run Code Online (Sandbox Code Playgroud)
但这不是常见的解决方案.create_wrap_function具有固定的函数格式,因为func_t限制了格式.
我们知道,Lua已关闭,也可以调用C函数.我想要实现的内容如下:我们要调用的函数是foo1和foo2,它们具有不同类型的args和返回值.
int foo1(int a) {
...
return intValue;
}
double foo2(char* str, double a) {
...
return dblValue;
}
Run Code Online (Sandbox Code Playgroud)
在C客户端中,调用函数如:
lua_returnValue returnValue1 = Do_Lua_Wrap(__FILE__, __LINE__, foo1, 1);
lua_returnValue returnValue2 = Do_Lua_Wrap(__FILE__, __LINE__, foo2, "string …Run Code Online (Sandbox Code Playgroud) 我想实现像在我的 Lua 构建中嵌入套接字功能一样的功能。所以我不需要再复制socket.core.dll(只是为了好玩)。
我搜索邮件列表,看到一些人讨论这个主题, http://lua-users.org/lists/lua-l/2005-10/msg00269.html
但我对详细步骤有疑问,谁可以给我更改 lua 和 luasocket 代码以使它们协同工作(而不是使用 dll 方法)的详细步骤。
我在 Windows XP 和 VC2008 中尝试了以下步骤:
1)将luasocket代码复制到Lua项目中。
2)添加一些代码
static const luaL_Reg lualibs[] = {
{"", luaopen_base},
{LUA_LOADLIBNAME, luaopen_package},
{LUA_TABLIBNAME, luaopen_table},
{LUA_IOLIBNAME, luaopen_io},
{LUA_OSLIBNAME, luaopen_os},
{LUA_STRLIBNAME, luaopen_string},
{LUA_MATHLIBNAME, luaopen_math},
{LUA_DBLIBNAME, luaopen_debug},
{LUA_SOCKETLIBNAME, luaopen_socket_core}, // add this line
{LUA_MIMELIBNAME, luaopen_socket_core}, // add this line
{NULL, NULL}
};
Run Code Online (Sandbox Code Playgroud)
3)构建项目,并运行它。
当我输入时print(socket._VERSION),它显示luasocket 2.0.2,它是正确的。
当我输入时print(socket.dns.toip("localhost")),它显示127.0.0.1 table: 00480AD0,它也是正确的。
但是当我尝试使用其他功能(例如绑定)时,它无法工作。
谁能告诉我原因?