SWIG_exception() 将 SWIG_RuntimeError 打印为字符串

Posted

技术标签:

【中文标题】SWIG_exception() 将 SWIG_RuntimeError 打印为字符串【英文标题】:SWIG_exception() prints SWIG_RuntimeError as string 【发布时间】:2018-06-05 17:04:06 【问题描述】:

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

在我的 typemap 中,我检查输入是否为表格。

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>

我尝试不包括&lt;std_except.i&gt; 和/或&lt;exception.i&gt;,但这些都没有解决问题。

我该如何解决这个问题?

【问题讨论】:

这里的实际问题是什么?您不希望它打印 SWIG_RuntimeError 还是要打印其他内容?请记住,Lua 不支持异常,因此 SWIG 将 C++ 异常转换为 Lua error SWIG 的 Lua 生成器只定义了 #define SWIG_exception(a,b) lua_pushfstring(L,"%s:%s",#a,b);SWIG_fail; #define SWIG_fail goto fail;fail 的块只是调用lua_error(L); @HenriMenke 当我在 Lua 中生成错误时,它们通常会像 [string "; function bang() ; pd.setArray("arr" , "123"..."]:1: expected a table 一样打印,这会准确显示错误发生的位置。然而,我的包装函数只是打印SWIG_RuntimeError:argument mismatch: table expected,它不像第一个那样提供信息,所以我认为SWIG_RuntimeError 应该转换为 Lua 中的其他字符串以指定错误发生的位置。但也许我错了。是否可以像我的第一个示例一样使用SWIG_exception() 使其自动打印? 如果你想知道错误在 Lua 代码中的位置,只需查看堆栈回溯。要查找错误在接口文件中的位置,您必须调整异常生成器,请参阅我的答案。 【参考方案1】:

如果您不喜欢 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 时,您总会得到一个。

【讨论】:

谢谢!我会给你赏金。

以上是关于SWIG_exception() 将 SWIG_RuntimeError 打印为字符串的主要内容,如果未能解决你的问题,请参考以下文章

如何将thinkcmf导入eclipse

如何将Ios文件上传到

Javascript 将正则表达式 \\n 替换为 \n,将 \\t 替换为 \t,将 \\r 替换为 \r 等等

如何将视频文件转换格式

sh 一个将生成CA的脚本,将CA导入到钥匙串中,然后它将创建一个证书并与CA签名,然后将其导入到

python怎么将0写入文件?