How to check Lua version in SWIG interface file?

假如想象 提交于 2019-12-24 08:48:29

问题


I have the below function which I would like to use only when the Lua version is equal to, or smaller than 5.1.

So I wrote it like the following in myBindings.i file:

/* used to backport lua_len to Lua 5.1 */
#if LUA_VERSION_NUM <= 501
%{
static void lua_len(lua_State *L, int i) 
{
    switch (lua_type(L, i)) 
    {
        case LUA_TSTRING:
            lua_pushnumber(L, (lua_Number)lua_objlen(L, i));
            break;
        case LUA_TTABLE:
            if (!luaL_callmeta(L, i, "__len"))
            lua_pushnumber(L, (lua_Number)lua_objlen(L, i));
            break;
        case LUA_TUSERDATA:
            if (luaL_callmeta(L, i, "__len"))
            break;
        default:
        luaL_error(L, "attempt to get length of a %s value",
                   lua_typename(L, lua_type(L, i)));
  }
}
%}
#endif

However when I compile the code, the compiler doesn't skip the lua_len function in Lua 5.3.

how can I expose lua_len function to the compiler depending on the version info?


回答1:


TL;DR: You have to move the preprocessor macros inside the literal block %{ ... %}.


In this scenario

#if CONDITION
%{
...
%}
#endif

the CONDITION is evaluated by SWIG. SWIG does not know about the macro LUA_VERSION_NUM because it is a priori interface agnostic (i.e. you could also generate a Python interface where LUA_VERSION_NUM has no meaning).

In the variant

%{
#if CONDITION
...
#endif
%}

SWIG will forward everything inside the literal block to the interface file. This will happen literally without any further inspection by SWIG, so preprocessor macros will be untouched. The C++ compiler will include <lua.hpp> and finds a definition of LUA_VERSION_NUM there, so the macro will have its intended effect.



来源:https://stackoverflow.com/questions/51349885/how-to-check-lua-version-in-swig-interface-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!