【问题标题】:Return class pointer to lua with luabind使用 luabind 将类指针返回到 lua
【发布时间】:2013-05-08 21:40:49
【问题描述】:

有什么方法可以在 C++ 函数中将指向类的指针返回给 lua? 除了其他更绝望的事情之外,我已经尝试过这个:

P* GetP()
{
    return g_P;
}

module(L)
[
    def("GetP", &GetP)
]

这会使程序在运行 main() 中的第一行之前就崩溃,即使代码只是位于从未调用过的函数中。

我以为是 luabind 不知道 P 是个问题,但我什至告诉它失败的原因。

module(L)
[
    class_<P>("ClassP")
    .def(constructor<>())
]

这可能是因为 P 的继承层次有点复杂,不确定。

class GO;
class L;
class C : public GO;
class P : public C, L;

我尝试了不同的方法来告诉 luabind P 的继承,但没有一个给出任何结果。

我得到的崩溃是 program.exe 中 0x0059a064 处的未处理异常:0xC0000005:访问冲突读取位置 0x00000004,在 xtree 中找到。

_Pairib insert(const value_type& _Val)
    {   // try to insert node with value _Val
        _Nodeptr _Trynode = _Root();
        _Nodeptr _Wherenode = _Myhead;
        bool _Addleft = true;   // add to left of head if tree empty

任何帮助表示赞赏。

【问题讨论】:

    标签: c++ lua luabind


    【解决方案1】:

    为什么要在 lua 代码中使用类指针?作为一个 C++ 类,它将是不透明的……或者更好。 ~微笑~

    也许在C++代码中设置了一个std::map,并将指针与哈希值一起存储在map中,并将哈希值传递给lua?然后 lua 可以使用它传回其他地方的 C++ 代码。

    编辑:您可以稍微取消对P 的引用,并传递一个散列来代替P 中的this

    请记住,thing:Method() 只是thing.Method( thing ) 的简写——因此,为thing 使用散列在很大程度上仍然是相同的构造,但在外观上少了一点OO。

    类似的东西会起作用......

    std::map<unsigned,P*> p_Map;
    
    void p_AddValue( unsigned hash, int aValue )
    {
        if( p_Map.find( hash ) != p_Map.end() )
            p_Map[hash]->AddValue( aValue );
    }
    
    unsigned p_New()
    {
        P* p = new P();
        unsigned hash;
    
        do hash = GenerateHash( p );
        while( p_Map.find( hash ) != p_Map.end() );
    
        p_Map[hash] = p;
    
        return hash;
    }
    
    module(L)
    [
        def("p_AddValue", &p_AddValue)
        def("p_New", &p_New)
    ]
    

    那么在 Lua 中你应该可以做这样的事情......

    local p1 = p_New();
    local p2 = p_New();
    
    p_AddValue( p1, 5 );
    p_AddValue( p2, 10 );
    

    等等

    这不是一个完美的解决方案,但它应该可以解决您遇到的问题。希望其他人可能会提出更好的答案?

    重新编辑:想一想,虽然有点麻烦,但可能还有另一种方法可以让您通过 Lua 中的代理类(间接)使用 P 类。 .

    class PProxy
    {
        protected:
    
           P  p;
    
        public:
    
           PProxy() : P() {};
           ~PProxy() {};
    
           void AddValue( int aValue ) { p.AddValue( aValue ); }
    }
    
    module(L)
    [
        class_<PProxy>("P")
        .def(constructor<>())
        .def("AddValue", &PProxy::AddValue)
    ]
    

    【讨论】:

    • 那么,如果我理解正确的话,你建议我在 P 和 lua 之间再增加一层抽象?例如,我没有将类的方法暴露给 lua,而是与它进行如下交互: [Block 1] 而不是:[Block 2] 唉,我没有让 标记工作,所以我使用了 pastebin :<a href="/default/index/tourl?u=aHR0cDovL3Bhc3RlYmluLmNvbS9zVDNTQlg2VQ%3D%3D" rel="nofollow" target="_blank">pastebin.com/sT3SBX6U</a>
    • 您的编辑确实有助于澄清它,我最终按照哈希解决方案做了一些事情。但我想我最终可能会将其更改为代理解决方案,如果我有时间重新使用它的话。不是我一直在寻找/希望的答案,但它确实解决了我遇到的问题。感谢您的宝贵时间。
    猜你喜欢
    • 2014-08-05
    • 2013-08-13
    • 2016-07-05
    • 2010-12-29
    • 2013-07-08
    • 2013-01-28
    • 1970-01-01
    • 2022-11-21
    • 1970-01-01
    相关资源
    最近更新 更多