`
tcspecial
  • 浏览: 896306 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

lua 调用C

    博客分类:
  • OS
阅读更多

   Lua 下通过虚拟栈传递参数,只要注册相应接口便可调用C函数。

 

#include "lua.h"		// v5.1.5
#include "lualib.h"
#include "lauxlib.h"

// 原生函数
int ShowVal(const char *szReq, int &score);

// 包装函数
int GetScore(lua_State *env)
{
    int count = lua_gettop(env);
    if (count != 1)
    {
        lua_pushstring(env, "Param size not equal 3");
        lua_error(env);
        return -1;
    }

    // 参数出栈
    const char *szReq = luaL_checkstring(env, 1);

    // 原生接口
    int code = 0, score = 0;
    code = ShowVal(szReq, &score);

    // 结果入栈
    lua_pushnumber(env, code);
    lua_pushnumber(env, score);
    return 2;	// 入栈参数个数
}

static luaL_Reg luaLibs[] =
{
    {"luaGetScore", GetScore},
    {NULL, NULL}
};

// lua接口注册
int luaopen_cloudadapi(lua_State *env)
{
    const char *const LIBRARY_NAME = "cloudadapi";
    luaL_register(env, LIBRARY_NAME, luaLibs);

    return 1;
}

 

编译动态库 cloudadapi.so 

 

测试:

require "cloudadapi"

code, score = cloudadapi.luaGetScore('test')
print(string.format("code:%d score:%d", code, score))

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics