无法将 Boost.Any 对象传递给 C++ Lua 绑定。

https://github.com/Rapptz/sol/ 是一个 C++11 Lua 绑定库,非常棒。

虽然我之前成功运行过 Sol 中的代码,但我无法正确地传递 Boost.Any 对象,并通过 Lua 解包。使用 unpack 作为 boost::any_cast 的别名,代码应该能够运行。我定义了一个新的数据类型,以便 Sol 可以正确调用 Boost.Any 对象的复制构造函数。

然而,当我使用 GDB 调试程序时,它给出了一个 SEGFAULT。 Lua 似乎在 Boost.Any 的复制构造函数内出错了。

我需要完全定义 Boost.Any 类吗?Lua 是否会自动调用 C++ 运算符,还是必须我自己做?我能够将任何运算符函数传递给 Lua 吗?还是 boost::any_cast 的问题?

我的理论是,也许我没有为 Lua 定义足够深的数据类型,无法充分利用 Boost.Any。

#include <iostream>
#include <string>
#include <sstream>
#include "lua.hpp"
#include "sol.hpp"

#include "Flexiglass.hpp"

template <class T>
T unpack (boost::any b)
{
    return boost::any_cast<T>(b);
}

int main()
{
    sol::state lua;
    lua.open_libraries(sol::lib::base);

    //This syntax should work here. I did a test case with a templated function.
    lua.set_function<std::string(boost::any)>("unpack", unpack);

    //In order to allow Sol to overload constructors, we do this.
    sol::constructors<sol::types<>,
                    sol::types<boost::any&>,
                    sol::types<boost::any&&>,
                    sol::types<std::string>> constructor;

    //This defines the new class that is exposed to Lua (supposedly)
    sol::userdata<boost::any> userdata("boost_any", constructor);

    //Instantiate an instance of the userdata to register it to Sol.
    lua.set_userdata(userdata);

    //Set boost::any object to a std::string value and pass it to Lua.
    boost::any obj("hello");
    lua.set("b", obj);

    //Contents:
    //print('Hello World!')
    //unpack(b)
    lua.open_file("test.lua");

    //The program outputs "Hello World"
    //But fails at the unpack() method.

    return 0;
}
点赞
用户3325075
用户3325075

我通过实现一个类似但可运行的 Boost.Any 版本,并在 set_function("NAME", function) 中实例化函数来解决了这个问题。

这样可以获得一个正确运行的系统,我能够在 C++ 中创建 Any 对象并将其传递给 Lua,或者在 Lua 中创建 Any 对象然后将其传递给 C++。只要我正确定义了如何在 C++ 和 Lua 之间交互类型,我就能够在两者之间打包和解包数据。这样一来,就创建了一个非常好的系统,可以轻松地扩展可供脚本使用的类型。

我认为我已经达到了目标,对于此事可能产生的任何其他想法,我都很感兴趣。

2015-04-08 08:24:24