1

有什么方法可以在 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

任何帮助表示赞赏。

4

1 回答 1

1

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

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

编辑:您可以取消引用P并传递一个哈希来代替thisin P

请记住,这thing:Method()只是简写thing.Method( thing )——因此,使用散列 forthing仍然在很大程度上是相同的构造,但在外观上少了一点 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)
]
于 2013-05-07T21:07:31.993 回答