c++ - 无法将 Boost.Any 对象传递给 C++ Lua 绑定(bind)

标签 c++ boost lua g++ runtime

https://github.com/Rapptz/sol/是 Sol,一个非常棒的 C++11 Lua 绑定(bind)。

虽然我之前已经设法在 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;
}

最佳答案

我设法解决了这个问题,方法是实现一个类似但功能正常的 Boost.Any 版本,然后通过实例化函数而不是在实际的 set_function 中,而是在 set_function("NAME", function );

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

我相信我现在已经达到了我的目标,并且对由此产生的任何其他想法感兴趣。

关于c++ - 无法将 Boost.Any 对象传递给 C++ Lua 绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29412250/

相关文章:

c++ - # 错误“线程支持不可用 : it has been explicitly disabled with BOOST_DISABLE_THREADS

linux - srlua makefile 错误 lua.h No such file or directory

c++ - 隐写术 : Encoded audio and video file not being played, 已损坏。什么问题

c++ - 为什么我可以在 main() 之前通过 std::map 填充变量?

c++ - cstdint 和 tr1/cstdint 之间的区别

c++ - 带有附加结果的 QCompleter

c++ - 具有 BOOST/CSTDINT 类型的 BOOST 稀疏 vector 数组;失败,为什么?

c++ - 我可以用 bind1st/2nd 替换 boost::bind 吗?

lua - Lua:如何找出元素是否是表格而不是字符串/数字?

sorting - 如何对这个lua表进行排序?