查看: 4|回复: 0

正确lua简单的扩展,可以加速相关C++数据。

[复制链接]

34

主题

51

回帖

1100

积分

金牌会员

积分
1100
发表于 昨天 10:04 | 显示全部楼层 |阅读模式
大家好,又见面了,我是全栈君。
很早的时候,我有一件事纠结。如果,我在这里C++打开界面脚本。使用C++其中一个目标,和。我的程序有很多不同的lua虚拟机。每个虚拟机与一个关联C++对象,它是多线程,那么如何快速应利用这个好时机lua_State针来定位到对象指针呢?
曾经我没有能力读懂lua的源代码,也能够说不知道关键部分怎样操作,我当时的做法。是利用临界区和std::map来解决这个问题的。非常明显这个方式的效率非常低非常低。
如今有能力读lua源代码了。当然有更有效的解决的方法了。由于在我们利用lua的过程中。lua_State这个结构指针是要贯穿全部用到lua的地方的,那么我就行对这个结构进行扩展,让它可以保存我的数据,仅仅须要保存一个指针就可以。
lua_State这个结构,定义在 lstate.h中   (lua.h中仅仅是作者为了不让用户可以主动訪问结构成员而定义的空结构指针。各种开源脚本引擎都是这样,为了安全性。大家懂的)
以lua5.2.3为例,该结构原始定义例如以下:
struct lua_State {   CommonHeader;   lu_byte status;   StkId top;  /* first free slot in the stack */   global_State *l_G;   CallInfo *ci;  /* call info for current function */   const Instruction *oldpc;  /* last pc traced */   StkId stack_last;  /* last free slot in the stack */   StkId stack;  /* stack base */   int stacksize;   unsigned short nny;  /* number of non-yieldable calls in stack */   unsigned short nCcalls;  /* number of nested C calls */   lu_byte hookmask;   lu_byte allowhook;   int basehookcount;   int hookcount;   lua_Hook hook;   GCObject *openupval;  /* list of open upvalues in this stack */   GCObject *gclist;   struct lua_longjmp *errorJmp;  /* current error recover point */   ptrdiff_t errfunc;  /* current error handling function (stack index) */   CallInfo base_ci;  /* CallInfo for first level (C calling Lua) */ };
那么对这个结构扩展之后例如以下:
struct lua_State {   CommonHeader;   lu_byte status;   StkId top;  /* first free slot in the stack */   global_State *l_G;   CallInfo *ci;  /* call info for current function */   const Instruction *oldpc;  /* last pc traced */   StkId stack_last;  /* last free slot in the stack */   StkId stack;  /* stack base */   int stacksize;   unsigned short nny;  /* number of non-yieldable calls in stack */   unsigned short nCcalls;  /* number of nested C calls */   lu_byte hookmask;   lu_byte allowhook;   int basehookcount;   int hookcount;   lua_Hook hook;   GCObject *openupval;  /* list of open upvalues in this stack */   GCObject *gclist;   struct lua_longjmp *errorJmp;  /* current error recover point */   ptrdiff_t errfunc;  /* current error handling function (stack index) */   CallInfo base_ci;  /* CallInfo for first level (C calling Lua) */   int __mydata;//这里 };
//同一时候添加两个lua接口,能够将函数接口放到lapi.c中,声明放到lua.h中就可以,或者你是发烧追求极限效率不在乎很多其它的扩展和更新的朋友,那么你能够用硬编码定位,__mydata的偏移是0x70。
LUA_API void lua_setmydata(lua_State *L, int data){  L->__mydata = data; }
LUA_API int lua_getmydata(lua_State *L){  return L->__mydata; }
这样就万事具备了,又一次编译lua,试试结果怎样:
更抽象一点的做法:
使用硬编码进行定位:  

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表