2015-04-02 43 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