SWIG_exception() 将 SWIG_RuntimeError 打印为字符串

SWIG_exception() prints SWIG_RuntimeError as string

我使用 SWIG 包装了我的 C++ 函数,因此我可以在 Lua 中使用它。

在我的类型图中,我检查输入是否为 table。

if (!lua_istable(L, 1)) {
      SWIG_exception(SWIG_RuntimeError, "argument mismatch: table expected");
    }

但如果在 Lua 中调用此方法,则打印的消息如下所示。

SWIG_RuntimeError:argument mismatch: table expected

我试图用 -3 替换 SWIG_RuntimeError 但它只是打印 -3 而不是 SWIG_RuntimeError.

我包括了以下内容

%include <stl.i>
%include <std_string.i>
%include <std_except.i>

%include <exception.i>
%include <typemaps.i>

我试过不包括 <std_except.i> and/or <exception.i> 但是 none 这些解决了问题。

我该如何解决这个问题?

如果您不喜欢 SWIG 的标准异常处理程序,您只需编写自己的异常处理程序即可。但是,这不能跨生成器移植。

这是我的界面文件:

%module typemaps

%{
#include <vector>
void test_typemap(std::vector<int>) {}
%}

%define lua_exception(msg)
    lua_pushfstring(L, "%s:%d: %s\n", __FILE__, __LINE__, msg);
    SWIG_fail;
%enddef

%typemap(in) std::vector<int> {
    if (!lua_istable(L, 1)) {
        lua_exception("expected table for first argument");
    }
}

void test_typemap(std::vector<int>);

这是 Lua 输入文件:

local typemaps = require("typemaps")
typemaps.test_typemap({1,2,3})
typemaps.test_typemap("not a table")

这是错误信息:

lua5.3: test.i:15: expected table for first argument

stack traceback:
    [C]: in function 'typemaps.test_typemap'
    test.lua:3: in main chunk
    [C]: in ?

第一行告诉我们接口文件出错的地方。然后,在堆栈回溯中,我们找到 Lua 输入文件中的错误位置,即在第三行 (test.lua:3) 中,我们尝试使用字符串调用 test_typemap。堆栈回溯实际上对 Lua 是通用的,与 SWIG 无关。当您致电 error.

时,您总会得到一个