您好,登錄后才能下訂單哦!
今天小編給大家分享一下C++如何實(shí)現(xiàn)與Lua相互調(diào)用的相關(guān)知識(shí)點(diǎn),內(nèi)容詳細(xì),邏輯清晰,相信大部分人都還太了解這方面的知識(shí),所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來(lái)了解一下吧。
從本質(zhì)上來(lái)看,其實(shí)說(shuō)是不存在所謂的C++與lua的相互調(diào)用。lua是運(yùn)行在C上的,簡(jiǎn)單來(lái)說(shuō)lua的代碼會(huì)被編譯成字節(jié)碼在被C語(yǔ)言的語(yǔ)法運(yùn)行。在C++調(diào)用lua時(shí),其實(shí)是解釋運(yùn)行l(wèi)ua文件編譯出來(lái)的字節(jié)碼。lua調(diào)用C++其實(shí)還是解釋運(yùn)行l(wèi)ua文件編譯出來(lái)的字節(jié)碼的語(yǔ)義是調(diào)用lua棧上的C++函數(shù)。
來(lái)看下面這段代碼:
C++
#include "Inc/lua.h" #include "Inc/lauxlib.h" #include "Inc/lualib.h" #include "Inc/lobject.h" } using std::cout; using std::endl; int CAdd(lua_State* L) { int a = lua_tonumber(L, 2); int b = lua_tonumber(L, 1);; int sum = a + b; lua_pushnumber(L, sum); return 1; } int main() { lua_State* L = luaL_newstate(); luaL_openlibs(L); lua_register(L, "CAdd", CAdd); int stat = luaL_loadfile(L, "Test.lua") | lua_pcall(L, 0, 0, 0); if (stat) { cout << "error" << endl; } else { cout << "succ" << endl; } lua_close(L); return 0; }
lua
local x = CAdd(1, 2) print("x = " .. tostring(x))
運(yùn)行結(jié)果:
考慮上述C++代碼luaL_loadfile去加載并調(diào)用lua,lua又調(diào)用了C++注冊(cè)到lua虛擬機(jī)里的CAdd函數(shù)并正確打印了返回值,結(jié)果如圖所示。到底發(fā)生了什么?
C++調(diào)用lua時(shí),是對(duì)lua代碼進(jìn)行編譯生成字節(jié)碼,在運(yùn)行時(shí)對(duì)字節(jié)碼使用C的語(yǔ)法解釋運(yùn)行。
對(duì)luaL_loadfile調(diào)試,跟到f_parser:
static void f_parser (lua_State *L, void *ud) { LClosure *cl; struct SParser *p = cast(struct SParser *, ud); int c = zgetc(p->z); /* read first character */ if (c == LUA_SIGNATURE[0]) { checkmode(L, p->mode, "binary"); cl = luaU_undump(L, p->z, p->name); } else { checkmode(L, p->mode, "text"); cl = luaY_parser(L, p->z, &p->buff, &p->dyd, p->name, c); } lua_assert(cl->nupvalues == cl->p->sizeupvalues); luaF_initupvals(L, cl); }
簡(jiǎn)單來(lái)說(shuō),parser根據(jù)輸入進(jìn)行詞法,語(yǔ)法分析進(jìn)行編碼生成閉包,然后推入棧中等待調(diào)用。來(lái)看幾個(gè)用到的數(shù)據(jù)結(jié)構(gòu)。
LClosure
typedef struct LClosure { ClosureHeader; struct Proto *p; UpVal *upvals[1]; //被捕獲的外局部變量 } LClosure;
這是lua的閉包,此外還有CClosure是c的閉包,下面lua調(diào)用C++會(huì)提到,它們被Closure聯(lián)合體包裹。
Proto
typedef struct Proto { CommonHeader; lu_byte numparams; /* number of fixed parameters */ lu_byte is_vararg; lu_byte maxstacksize; /* number of registers needed by this function */ int sizeupvalues; /* size of 'upvalues' */ int sizek; /* size of 'k' */ int sizecode; int sizelineinfo; int sizep; /* size of 'p' */ int sizelocvars; int linedefined; /* debug information */ int lastlinedefined; /* debug information */ TValue *k; /* constants used by the function */ Instruction *code; //codes struct Proto **p; /* functions defined inside the function */ int *lineinfo; /* map from opcodes to source lines (debug information) */ LocVar *locvars; /* information about local variables (debug information) */ Upvaldesc *upvalues; /* upvalue information */ struct LClosure *cache; /* last-created closure with this prototype */ TString *source; /* used for debug information */ GCObject *gclist; } Proto;
Instruction *code;注意這個(gè)變量,這個(gè)變量就是指向我們編譯后生成字節(jié)碼數(shù)組的指針。
FuncState
typedef struct FuncState { Proto *f; /* current function header */ struct FuncState *prev; /* enclosing function */ struct LexState *ls; /* lexical state */ struct BlockCnt *bl; /* chain of current blocks */ int pc; /* next position to code (equivalent to 'ncode') */ int lasttarget; /* 'label' of last 'jump label' */ int jpc; /* list of pending jumps to 'pc' */ int nk; /* number of elements in 'k' */ int np; /* number of elements in 'p' */ int firstlocal; /* index of first local var (in Dyndata array) */ short nlocvars; /* number of elements in 'f->locvars' */ lu_byte nactvar; /* number of active local variables */ lu_byte nups; /* number of upvalues */ lu_byte freereg; /* first free register */ } FuncState;
FuncState互相是嵌套的,外部FuncState保存了內(nèi)部的部分信息,最外部的FuncState的f成員保存了編譯的所有字節(jié)碼,并傳遞給閉包LClosure。
以加載lua腳本為例。
f_parser調(diào)用luaY_parser分析,并初始化Upvalues(外局部變量)。
luaY_parser 使用LexState包裹FuncState調(diào)用luaX_next進(jìn)行進(jìn)一步分析,其結(jié)果保存到Proto結(jié)構(gòu)的code數(shù)組中,傳遞給LClosure并推入棧中。
luaX_next循環(huán)分析,依據(jù)詞法,語(yǔ)法規(guī)則調(diào)用luaK_code生成字節(jié)碼。
部分代碼:
static void statement (LexState *ls) { int line = ls->linenumber; /* may be needed for error messages */ enterlevel(ls); switch (ls->t.token) { case ';': { /* stat -> ';' (empty statement) */ luaX_next(ls); /* skip ';' */ break; } case TK_IF: { /* stat -> ifstat */ ifstat(ls, line); break; } //..................... } }
編譯代碼后,便可對(duì)閉包進(jìn)行解析運(yùn)行了。調(diào)試代碼上述 lua_pcall(L, 0, 0, 0) 代碼,跟到luaD_call:
void luaD_call (lua_State *L, StkId func, int nResults) { if (++L->nCcalls >= LUAI_MAXCCALLS) stackerror(L); if (!luaD_precall(L, func, nResults)) /* is a Lua function? */ luaV_execute(L); /* call it */ L->nCcalls--; } }
首先調(diào)用luaD_precall進(jìn)行預(yù)備工作,lua_state擴(kuò)展base_ci(CallInfo類(lèi)型)數(shù)組創(chuàng)建一個(gè)新元素保存括虛擬機(jī)的指令指針(lua_state->savedpc)在內(nèi)的調(diào)用堆棧的狀態(tài)以便調(diào)用結(jié)束后恢復(fù)調(diào)用堆棧,并把指令指針指向該閉包的指令數(shù)組(Closure->p->codes)。
然后調(diào)用luaV_execute循環(huán)取出指令運(yùn)行。
luaV_execute解釋執(zhí)行部分代碼:
void luaV_execute (lua_State *L) { CallInfo *ci = L->ci; LClosure *cl; TValue *k; StkId base; ci->callstatus |= CIST_FRESH; /* fresh invocation of 'luaV_execute" */ newframe: /* reentry point when frame changes (call/return) */ lua_assert(ci == L->ci); cl = clLvalue(ci->func); /* local reference to function's closure */ k = cl->p->k; /* local reference to function's constant table */ base = ci->u.l.base; /* local copy of function's base */ /* main loop of interpreter */ for (;;) { Instruction i; StkId ra; vmfetch(); vmdispatch (GET_OPCODE(i)) { vmcase(OP_MOVE) { setobjs2s(L, ra, RB(i)); vmbreak; } //............................ } }
CallInfo
函數(shù)執(zhí)行時(shí),lua_state通過(guò)CallInfo 數(shù)據(jù)結(jié)構(gòu)了解函數(shù)的狀態(tài)信息,并通過(guò)CallInfo組base_ci的上下生長(zhǎng)來(lái)維護(hù)調(diào)用堆棧。
typedef struct CallInfo { StkId func; /* function index in the stack */ StkId top; /* top for this function */ struct CallInfo *previous, *next; /* dynamic call link */ union { struct { /* only for Lua functions */ StkId base; /* base for this function */ const Instruction *savedpc; } l; struct { /* only for C functions */ lua_KFunction k; /* continuation in case of yields */ ptrdiff_t old_errfunc; lua_KContext ctx; /* context info. in case of yields */ } c; } u; ptrdiff_t extra; short nresults; /* expected number of results from this function */ unsigned short callstatus; } CallInfo;
lua調(diào)用C++,是上述C++調(diào)用lua時(shí)即c的語(yǔ)法解釋運(yùn)行l(wèi)ua代碼生成的字節(jié)碼的一種情況,即取出lua狀態(tài)機(jī)全局表中的CClosure中的函數(shù)指針運(yùn)行。
來(lái)看下向lua狀態(tài)機(jī)注冊(cè)C++函數(shù)lua_register
#define lua_pushcfunction(L,f) lua_pushcclosure(L, (f), 0) #define lua_register(L,n,f) (lua_pushcfunction(L, (f)), lua_setglobal(L, (n))) LUA_API void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n) { lua_lock(L); if (n == 0) { setfvalue(s2v(L->top), fn); api_incr_top(L); } else { CClosure *cl; api_checknelems(L, n); api_check(L, n <= MAXUPVAL, "upvalue index too large"); cl = luaF_newCclosure(L, n); cl->f = fn; L->top -= n; while (n--) { setobj2n(L, &cl->upvalue[n], s2v(L->top + n)); /* does not need barrier because closure is white */ } setclCvalue(L, s2v(L->top), cl); api_incr_top(L); luaC_checkGC(L); } lua_unlock(L); }
可以看到這里最終創(chuàng)建了一個(gè)CCloseure,包裹住lua_CFunction類(lèi)型的函數(shù)指針并推入棧頂和放入全局表中。
typedef int (*lua_CFunction) (lua_State *L); typedef struct CClosure { ClosureHeader; lua_CFunction f; TValue upvalue[1]; /* list of upvalues */ } CClosure;
可以看到CClosure包含了一個(gè)lua_CFunction類(lèi)型的函數(shù)指針和upvalue的鏈表
循環(huán)解釋字節(jié)碼語(yǔ)義的關(guān)于調(diào)用的部分
void luaV_execute (lua_State *L, CallInfo *ci) { //... vmcase(OP_CALL) { int b = GETARG_B(i); int nresults = GETARG_C(i) - 1; if (b != 0) /* fixed number of arguments? */ L->top = ra + b; /* top signals number of arguments */ /* else previous instruction set top */ ProtectNT(luaD_call(L, ra, nresults)); vmbreak; } //... }
可以看到調(diào)用語(yǔ)義的解釋調(diào)用了luaD_call
void luaD_call (lua_State *L, StkId func, int nresults) { lua_CFunction f; retry: switch (ttypetag(s2v(func))) { case LUA_VCCL: /* C closure */ f = clCvalue(s2v(func))->f; goto Cfunc; case LUA_VLCF: /* light C function */ f = fvalue(s2v(func)); Cfunc: { int n; /* number of returns */ CallInfo *ci = next_ci(L); checkstackp(L, LUA_MINSTACK, func); /* ensure minimum stack size */ ci->nresults = nresults; ci->callstatus = CIST_C; ci->top = L->top + LUA_MINSTACK; ci->func = func; L->ci = ci; lua_assert(ci->top <= L->stack_last); if (L->hookmask & LUA_MASKCALL) { int narg = cast_int(L->top - func) - 1; luaD_hook(L, LUA_HOOKCALL, -1, 1, narg); } lua_unlock(L); n = (*f)(L); /* do the actual call */ lua_lock(L); api_checknelems(L, n); luaD_poscall(L, ci, n); break; } //...
可以看到這里取到了上述Closure中的函數(shù)指針并進(jìn)行調(diào)用。
以上就是“C++如何實(shí)現(xiàn)與Lua相互調(diào)用”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會(huì)為大家更新不同的知識(shí),如果還想學(xué)習(xí)更多的知識(shí),請(qǐng)關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。