luabridge绑定c++返回指针的函数,和绑定c++返回对象的函数区别

示例

返回对象写法
MatTest createMatTest(string txt) {
	MatTest res(txt);
	return res;
};

//返回指针写法
MatTest* createMatTest1(string txt) {
	return new MatTest(txt);
};

返回对象的写法lua自动释放内存
返回指针的对象自己释放内存

指针存储对象

/**
  Wraps a pointer to a class object inside a Lua userdata.

  The lifetime of the object is managed by C++.
*/
class UserdataPtr : public Userdata
{
private:
    UserdataPtr(UserdataPtr const&);
    UserdataPtr operator=(UserdataPtr const&);

private:
    /** Push a pointer to object using metatable key.
     */
    static void push(lua_State* L, const void* p, void const* const key)
    {
        new (lua_newuserdata(L, sizeof(UserdataPtr))) UserdataPtr(const_cast<void*>(p));
        lua_rawgetp(L, LUA_REGISTRYINDEX, key);
        if (!lua_istable(L, -1))
        {
            lua_pop(L, 1); // possibly: a nil
            throw std::logic_error("The class is not registered in LuaBridge");
        }
        lua_setmetatable(L, -2);
    }

返回对象

template<class T>
class UserdataValue : public Userdata
{
private:
    UserdataValue(UserdataValue<T> const&);
    UserdataValue<T> operator=(UserdataValue<T> const&);

    char m_storage[sizeof(T)];

private:
    /**
      Used for placement construction.
    */
    UserdataValue() { m_p = 0; }

    ~UserdataValue()
    {
        if (getPointer() != 0)
        {
            getObject()->~T();
        }
    }

public:
    /**
      Push a T via placement new.

      The caller is responsible for calling placement new using the
      returned uninitialized storage.

      @param L A Lua state.
      @returns An object referring to the newly created userdata value.
    */
    static UserdataValue<T>* place(lua_State* const L)
    {
        UserdataValue<T>* const ud =
            new (lua_newuserdata(L, sizeof(UserdataValue<T>))) UserdataValue<T>();
        lua_rawgetp(L, LUA_REGISTRYINDEX, detail::getClassRegistryKey<T>());
        if (!lua_istable(L, -1))
        {
            throw std::logic_error("The class is not registered in LuaBridge");
        }
        lua_setmetatable(L, -2);
        return ud;
    }

    /**
      Push T via copy construction from U.

      @tparam U A container type.
      @param  L A Lua state.
      @param  u A container object reference.
    */
    template<class U>
    static inline void push(lua_State* const L, U const& u)
    {
        UserdataValue<T>* ud = place(L);
        new (ud->getObject()) U(u);
        ud->commit();
    }

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值