【问题标题】:Stack unwinding in C++ when using Lua使用 Lua 时在 C++ 中展开堆栈
【发布时间】:2010-10-23 20:14:36
【问题描述】:

我最近偶然发现了这个 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 的堆栈是否正确展开。会出什么问题吗?

【问题讨论】:

  • 当你提到 Luabind 时,我很困惑。 Luabind 本身是一个 C++ 库,但是看起来你怎么也没有使用它?

标签: c++ lua destructor stack-unwinding


【解决方案1】:

如果我理解正确,Luabind 抛出异常的函数无论如何都会被正确捕获和翻译。 (见reference。)

所以每当你需要指出错误时,只需抛出一个标准异常:

void function_for_lua( lua_State* L )
{
    std::string s("Trouble coming!");
    /* ... */

    // translated into lua error
    throw std::runtime_error("something went wrong");
}

免责声明:我从未使用过 Lubind。

【讨论】:

  • @Armen:必须让人们保持警觉。
猜你喜欢
  • 2011-12-13
  • 2014-04-17
  • 2011-09-24
  • 1970-01-01
  • 2016-11-03
  • 1970-01-01
  • 2011-07-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多