c++ - 如何检查 SWIG 接口(interface)文件中的 Lua 版本?

标签 c++ lua c-preprocessor swig

我有下面的函数,我只想在 Lua 版本等于或小于 5.1 时使用。

所以我在myBindings.i 文件中这样写:

/* 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

但是当我编译代码时,编译器不会跳过 Lua 5.3 中的 lua_len 函数。

如何根据版本信息将 lua_len 函数暴露给编译器?

最佳答案

TL;DR:您必须将预处理器宏移动到文字 block %{ ... %} 中.


在这种情况下

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

CONDITION由 SWIG 评估。 SWIG 不知道宏 LUA_VERSION_NUM因为它是一个先验接口(interface)不可知论者(即你也可以生成一个 Python 接口(interface),其中 LUA_VERSION_NUM 没有意义)。

在变体中

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

SWIG 会将文字 block 内的所有内容转发到接口(interface)文件。这将在没有 SWIG 进一步检查的情况下发生,因此预处理器宏将保持不变。 C++ 编译器将包含 <lua.hpp>并找到 LUA_VERSION_NUM 的定义在那里,所以宏将达到预期的效果。

关于c++ - 如何检查 SWIG 接口(interface)文件中的 Lua 版本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51349885/

相关文章:

string - 使用 string.match 处理语音标记

c - 将数字四舍五入为 int 大小边界字节数的方法

c++ - 在 OSX 上通过 dlopen 打开库时调试崩溃

c++ - 是可调用和模糊调用 : bug in either g++ or clang

scripting - VB6 - Lua 集成

c - 使用 unifdef 默认省略未定义的预处理器分支的方法?

c++ - 预处理器tomfoolery(字符串化#include)

c++ - 内部 lambda 中的悬空引用

c++ - 从控制台灵气解析多行

c++ - 使用宿主 C++ 应用程序编译 Lua 源代码