luabind 0.9.1仅使用STL迭代器显示一个元素。

我在使用luabind将stl::vector::iterator返回给lua脚本时遇到了奇怪的问题。

以下是代码:

1)我创建了两个函数,它们由lua脚本调用:

std::vector<car*> get_car_list()
{
    std::vector<car*>* vec = new std::vector<car*>();
    vec->push_back(new car("I'm the 1st"));
    vec->push_back(new car("I'm the 2nd"));
    return *vec;
}

void output(const std::string& msg)
{
    std::cout << "lua:" << msg << std::endl;
}

2)我将函数绑定到lua

luabind::module(L)
[
    luabind::def("get_car_list", &get_car_list, luabind::return_stl_iterator)
];

luabind::module(L)
[
    luabind::def("output", &output)
];

3)我按以下方式执行脚本:

function test()
    items  = get_car_list();
    for item in items do
        output(item:get_name());
    end
end

4)结果是: 在输出窗口中,只显示:

lua:I'm the 1st

程序在luabind/policy.hpp:754中中断

template <>
struct default_converter<std::string>
  : native_converter_base<std::string>
{
    .....

    void to(lua_State* L, std::string const& value)
    {
        lua_pushlstring(L, value.data(), value.size()); // !!Break Here with Error EXC_BAD_ACCESS
    }
};

我想显示std::vector中的所有元素,但它只显示第一个并崩溃了。

非常感谢你! :)

Jason

原文链接 https://stackoverflow.com/questions/7396856

点赞
stackoverflow用户329564
stackoverflow用户329564

我看到两个问题:

您使用指针和 new,好像我们在使用 Java,但实际上这是 C ++。如果按照这种方式使用 C ++,您将遇到明显的内存泄漏问题。

除非您有特殊的原因,否则应该这样做:

std::vector<car> get_car_list() {
    std::vector<car> vec;
    vec.push_back( car("我是第一辆车"));
    vec.push_back( car("我是第二辆车"));
    return vec; }

但您的代码还存在第二个问题:

显然, return_stl_iterator 假设在使用它时 STL 容器仍然存在,并且仅存储到该容器的迭代器。

因此,您不能像这样返回容器的拷贝,因为在您想要使用迭代器时该容器将不存在。这就像在使用临时容器的引用一样。

luabind doc 中所示的示例,return_stl_iterator 的想法是拥有一个仍然可访问的容器。在该示例中,容器存在于结构中。这不是临时的。

您可能会想通过 new 来分配向量,并在 get_car_list 函数中返回对此向量的引用。但不要这样做:您什么时候释放容器呢?

如果您想返回一个不存在于其他地方的向量(向量的临时拷贝),则不应使用 return_stl_iterator 策略,因为它似乎并不是为此而设计的。

2011-09-13 05:50:23