lua调c动态库【转】

Lua脚本调c动态库函数时开始调不成功,通过Lua官方的Mail List才知道:c动态库里的注册函数和Lua脚本的打开库的方式要一致。

1.

c动态库的代码:

static int lua_msgbox(lua_State* L)

{

    const char* message = luaL_checkstring(L, 1);

    const char* caption = luaL_optstring(L, 2, "");

    int result = MessageBox(NULL, message, caption, MB_YESNO);

    lua_pushnumber(L, result);

    return 1;

}

int __declspec(dllexport) luaopen_dllforlua(lua_State* L)

{

    lua_register(L, "msgbox",  lua_msgbox); //使用lua_register注册函数 

    return 1;

}

使用lua_register函数,则Lua脚本应该写成:

dllforlua = package.loadlib("dllforlua.dll", "luaopen_dllforlua")

dllforlua()

msgbox("Hey, it worked!", "Lua Message Box")

 

2.

static int lua_msgbox(lua_State* L)

{

    const char* message = luaL_checkstring(L, 1);

    const char* caption = luaL_optstring(L, 2, "");

    int result = MessageBox(NULL, message, caption, MB_YESNO);

    lua_pushnumber(L, result);

    return 1;

}

static const  luaL_Reg mylib[] =

{

    {"msgbox", lua_msgbox},

    {NULL, NULL}

};

int __declspec(dllexport) luaopen_dllforlua(lua_State* L)

{

    luaL_register(L, "dllforlua", mylib);//使用luaL_register注册函数

    return 1;

}

使用luaL_register函数,则Lua脚本应该写成:

require("dllforlua")

dllforlua.msgbox("Hey, it worked!", "Lua Message Box")


原文链接:http://blog.csdn.net/sumoyu/article/details/2581928

你可能感兴趣的:(lua调c动态库【转】)