gpt4 book ai didi

c++ - SWIG_exception() 将 SWIG_RuntimeError 打印为字符串

转载 作者:太空狗 更新时间:2023-10-29 22:55:39 24 4
gpt4 key购买 nike

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

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

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>但这些都没有解决问题。

我该如何解决这个问题?

最佳答案

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

这是我的接口(interface)文件:

%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 ?

第一行告诉我们接口(interface)文件中出错的地方。在堆栈回溯中,我们然后找到 Lua 输入文件中哪里出了问题,即在第三行 (test.lua:3) 我们尝试调用 test_typemap字符串。堆栈回溯实际上是 Lua 通用的,与 SWIG 无关。当您调用 error 时,您总会得到一个。

关于c++ - SWIG_exception() 将 SWIG_RuntimeError 打印为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50705443/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com