码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-07-27 22:52:15      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:

很早的时候,我有一件事纠结。如果,我在这里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,试试结果怎样:

技术分享


更抽象一点的做法:

技术分享





使用硬编码进行定位:
技术分享

版权声明:本文博客原创文章,博客,未经同意,不得转载。

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

标签:

原文地址:http://www.cnblogs.com/yxwkf/p/4681342.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!