Fork me on GitHub

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

转载自:http://www.cnblogs.com/egmkang/archive/2012/07/01/2572064.html

 

题目不知道怎么取才好,但是意思很简单:

如果你暴露一个复杂对象给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......

posted @   江湖码客Mark  阅读(612)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示