2015-04-02 41 views
2

https://github.com/Rapptz/sol/是Sol,一个C++ 11 Lua绑定,令人惊叹。无法将Boost.Any对象传递给C++ Lua绑定

虽然我设法在Sol之前正确运行代码,但我一直无法正确传递一个Boost.Any对象并通过Lua解压缩它。解包是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; 
} 

回答

1

我已经设法通过实现类似,但功能Boost.Any的版本,然后实现通过实例化功能不会在实际set_function具有约束力的解决这个问题,但在set_function(“NAME” ,功能);

这导致一个正常运行的系统,我可以在C++中创建任何对象并将它们传递给Lua,或者我可以在Lua中创建任何对象,然后将它们传递给C++。只要我正确地定义了如何来回接口类型,我就能够将数据解包和打包出C++和Lua。总之,这创建了一个伟大的系统,可以轻松扩展可能暴露给脚本的类型。

我相信我现在已经达到了我的目标,并对可能来自此的任何其他想法感兴趣。

+0

我想要一个额外的答案,可能会解释一个Boost.Any实现和集成使用Sol或类似的C++ 11/Lua绑定,因为Boost.Any源代码很厚。 – Cinch 2015-04-08 08:25:08