SWIG_exception()将SWIG_RuntimeError打印为字符串

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

在我的typemap中,我检查输入是否是table。

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

但如果在Lua中调用此函数,则消息会打印如下所示。

SWIG_RuntimeError:argument mismatch: table expected

我尝试将SWIG_RuntimeError替换为-3,但然后它只打印-3而不是SWIG_RuntimeError

我包含了以下内容

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

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

我尝试不包含<std_except.i>和/或<exception.i>,但这些都没有解决问题。

我该如何解决这个问题?

点赞
用户1944004
用户1944004

如果您不喜欢 SWIG 的标准异常处理程序,则可以编写自己的异常处理程序。然而,这对于不同的生成器来说并不具有可移植性。

这是我的接口文件:


%{
#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 无关。在调用错误时总是会得到一个回溯。

2018-06-06 07:07:06