使用 luabind 将类指针返回给 Lua。

有没有办法在 C++ 函数中返回指向 Lua 的类的指针?

我尝试过这个,还有其他更绝望的方法:

P* GetP()
{
    return g_P;
}

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

这会导致程序甚至在运行 main() 的第一行之前崩溃,即使代码只是停留在从未调用的函数中。

我认为这是一个问题,P对 luabind而言是未知的,但即使告诉它是什么也失败了。

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

这可能是因为P具有相当复杂的继承层次结构,不确定。

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

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

我收到的崩溃是一个 Unhandled exception at 0x0059a064 in program.exe: 0xC0000005: Access violation reading location 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

任何帮助都会受到赞赏。

点赞
用户2192592
用户2192592

为什么你想要 Lua 代码中的类指针?作为一个 C++ 类,它应该是不透明的...或者最好是这样。微笑

或许在 C++ 代码中建立一个 std::map,并使用哈希值将指针存储在映射中,然后将哈希值传递给 Lua?然后 Lua 可以将其传回到其他地方的 C++ 代码中使用。

编辑: 你可以解除对 P 的引用并传递哈希值作为 P 中的 this 替代品。

请记住,thing:Method() 只是 thing.Method(thing) 的缩写,因此,为 thing 使用哈希仍然基本上是相同的结构,但在视觉上看起来不那么面向对象。

类似于这样的代码应该能够工作...

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-07 21:07:31