将C语言指针推入堆栈,获取表格。

在 C 代码中有两个函数定义:

static int luaMp4_load(lua_State *L){
    LPP_Mp4 *ret = LPP_Mp4Load(luaL_checkstring(L, 1));
    *pushMp4(L) = ret;
    return(1);
}
static int luaMp4_play(lua_State *L){
    LPP_Mp4Play(*toMp4(L, 1), luaL_checknumber(L, 2));
    return 0;
}

然后在 Lua 中按顺序调用它们:

Mp4.load(movie)
Mp4:play(60)

pushMp4toMp4 是下面这两个函数:

LPP_Mp4** toMp4 (lua_State *L, int index){
    LPP_Mp4** handle  = (LPP_Mp4**)lua_touserdata(L, index);
    if (handle == NULL) luaL_typerror(L, index, "Mp4");
    return handle;
}
LPP_Mp4** pushMp4(lua_State *L) {
    LPP_Mp4** newvalue = (LPP_Mp4**)lua_newuserdata(L, sizeof(LPP_Mp4*));
    lua_getfield(L, LUA_REGISTRYINDEX, "Mp4");
    lua_setmetatable(L, -2);
    return newvalue;
}

问题是,在 luaMp4_play 中我得到一个空的 handle,此外还提示堆栈第一个元素是一个“table”(而不是期望的“Mp4”) - 在 luaL_typerror(lua_State *L, int narg, const char *tname) 函数中:

const char *msg = lua_pushfstring(L, "%s expected, got %s",
                                tname, lua_typename(L, lua_type(L,(narg))));

如何解决这个问题?

编辑:

LPP_Mp4 结构体:

typedef struct {
    struct mp4_read_struct reader;
    Mp4AvcNalStruct nal;
    struct mp4_video_read_output_struct v_packet;
    Mp4AvcDecoderStruct *avc;
    Mp4AvcCscStruct *csc;
} LPP_Mp4;

lua_touserdata 是一个 Lua API 库函数:

LUA_API void *lua_touserdata (lua_State *L, int idx) {
  StkId o = index2adr(L, idx);
  switch (ttype(o)) {
    case LUA_TUSERDATA: return (rawuvalue(o) + 1);
    case LUA_TLIGHTUSERDATA: return pvalue(o);
    default: return NULL;
  }
}

https://github.com/lua/lua/blob/master/src/lapi.c - 第 413 行

点赞
用户5139327
用户5139327

我对 C 代码中的 return (1); 感到困惑,并且毫不怀疑 Mp4:load() 返回任何值。

感谢 Etan Reisner 指出了这一点,并且使用以下代码解决:

mv = Mp4.load(movie)
mv:play(60)
2015-07-21 14:44:22