[tolua++]tolua++中暴露對象給lua時,一定要把解構函式暴露給lua

來源:互聯網
上載者:User

標籤:

題目不知道怎麼取才好,但是意思很簡單:

如果你暴露一個複雜物件給Lua,實作類別似於OO編程的話,那麼也要把解構函式暴露給Lua.

否則的話,lua gc的時候,回收垃圾對象,沒有找到回收函數,就直接free掉了,這在C++中,是相當致命的.

 

tolua++中的tolua_cclass函數,用來註冊lua對象,

TOLUA_API void tolua_cclass (lua_State* L, const char* lname, const char* name, const char* base, lua_CFunction col)

 同時會把最後的那個參數col,註冊到lua對象的元表裡面:

static void push_collector(lua_State* L, const char* 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,如果沒找到,就用default的析構,否則就用使用者提供的解構函式:

top = lua_gettop(L);if (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,".collector");    lua_rawget(L,-2);           /* stack: gc umt mt collector */    if (lua_isfunction(L,-1)) {        /*fprintf(stderr, "Found .collector!\n");*/    }    else {        lua_pop(L,1);        /*fprintf(stderr, "Using default cleanup\n");*/        lua_pushcfunction(L,<strong>tolua_default_collect</strong>);//這個是預設的解構函式    }     lua_pushvalue(L,1);         /* stack: gc umt mt collector u */    lua_call(L,1,0);

 而預設的解構函式是C free的簡單封裝:

TOLUA_API int tolua_default_collect (lua_State* tolua_S){ void* self = tolua_tousertype(tolua_S,1,0); free(self); return 0;}

 

如果你通過tolua++註冊一個複雜類型給lua的話,解構函式不被調用,而直接調用了free,會發生很多未定義行為.

這就是在我們伺服器中隱藏了超過兩年的一個Bug......

[tolua++]tolua++中暴露對象給lua時,一定要把解構函式暴露給lua

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.