加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

tolua++中暴露对象给lua时,一定要把析构函数暴露给lua

发布时间:2020-12-14 22:12:28 所属栏目:大数据 来源:网络整理
导读:注册一个复杂对象给Lua,也要把析构函数注册到Lua. 否则,lua gc的时候,回收垃圾对象,没有找到回收函数,就调用默认的析构函数,直接释放了对象内存。 ? tolua++中的tolua_cclass函数,用来注册lua对象, TOLUA_API void ? tolua_cclass (lua_State* L, const ? ch

注册一个复杂对象给Lua,也要把析构函数注册到Lua.

否则,lua gc的时候,回收垃圾对象,没有找到回收函数,就调用默认的析构函数,直接释放了对象内存。

?

tolua++中的tolua_cclass函数,用来注册lua对象,

TOLUA_API void? tolua_cclass (lua_State* L, const? char * lname,monospace!important; min-height:inherit!important">* name,monospace!important; min-height:inherit!important">* base,lua_CFunction col)

?同时会把回收函数(最后的那个参数col),注册到lua对象的元表里面:

static? push_collector(lua_State* L,monospace!important; min-height:inherit!important">* type,lua_CFunction col) {
?
???? /* push collector function,but only if it's not NULL,or if there's no
??????? collector already */
???? if? (!col) return ;
???? luaL_getmetatable(L,type);
lua_pushstring(L, ".collector" );
???????? //....
lua_pushcfunction(L,col);
//....

?而发生gc的时候,class_gc_event函数会去在lua对象的元表里面找".collector"这个key,如果没找到,就用默认的析构函数,否则就用用户提供的析构函数:

top = lua_gettop(L);
(tolua_fast_isa(L,top,top-1,lua_upvalueindex(2))) /* make sure we collect correct type */
{
/*fprintf(stderr,"Found type!n");*/
/* get gc function */
lua_pushliteral(L,monospace!important; min-height:inherit!important">);
lua_rawget(L,-2);?????????? /* stack: gc umt mt collector */
(lua_isfunction(L,-1)) {
}
else? {
???????? lua_pop(L,1);
//这个是默认的析构函数
}
?
lua_pushvalue(L,1);???????? /* stack: gc umt mt collector u */
lua_call(L,1,0);

?而默认的析构函数是C free的简单封装:

TOLUA_APIint? tolua_default_collect (lua_State* tolua_S)
{
? void * self = tolua_tousertype(tolua_S,0);
? free (self);
return? 0;
}

如果你通过tolua++注册一个复杂类型给lua的话,析构函数不被调用,而直接释放对象内存,会发生很多未定义行为.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读