C++ 中的堆栈展开使用Lua时
我最近偶然发现了这个 C++/Lua 错误
int function_for_lua( lua_State* L )
{
std::string s("Trouble coming!");
/* ... */
return luaL_error(L,"something went wrong");
}
该错误是 luaL_error
使用 longjmp
,因此堆栈永远不会展开,并且 s
永远不会被破坏,泄漏内存。还有一些 Lua API 无法展开堆栈。
一种显而易见的解决方案是在 C++ 模式下编译 Lua,但有例外。然而,我不能,因为 Luabind 需要标准 C ABI。
我目前的想法是编写自己的函数来模仿 Lua API 的麻烦部分:
// just a heads up this is valid c++. It's called a function try/catch.
int function_for_lua( lua_State* L )
try
{
/* code that may throw Lua_error */
}
catch( Lua_error& e )
{
luaL_error(L,e.what());
}
所以我的问题是:function_for_lua
的堆栈是否正确展开。会出什么问题吗?
I recently stumbled into this this C++/Lua error
int function_for_lua( lua_State* L )
{
std::string s("Trouble coming!");
/* ... */
return luaL_error(L,"something went wrong");
}
The error is that luaL_error
use longjmp
, so the stack is never unwound and s
is never destructed, leaking memory. There are a few more Lua API's that fail to unwind the stack.
One obvious solution is to compile Lua in C++ mode with exceptions. I, however, cannot as Luabind needs the standard C ABI.
My current thought is to write my own functions that mimic the troublesome parts of the Lua API:
// just a heads up this is valid c++. It's called a function try/catch.
int function_for_lua( lua_State* L )
try
{
/* code that may throw Lua_error */
}
catch( Lua_error& e )
{
luaL_error(L,e.what());
}
So my question: Is function_for_lua
's stack properly unwound. Can something go wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果我理解正确的话,无论如何,使用
Luabind
函数抛出异常都会被正确捕获和翻译。 (请参阅参考。)因此,每当您需要指示错误时,只需抛出标准异常:
免责声明:我从未使用过 Lubind。
If I understand correctly, with
Luabind
functions that throw exceptions are properly caught and translated anyway. (See reference.)So whenever you need to indicate an error, just throw a standard exception:
Disclaimer: I've never used Lubind.