首先新建一个cpp项目,命名为cppLibForLua,把lua的库引入,添加如下文件,编译成DLL
GameHelp.h
#ifdef GAME_HELP_API #define API __declspec(dllexport) #else #define API __declspec(dllimport) #endif extern "C" { API int fastPow(lua_State *L); API int luaopen_MyLuaDLL(lua_State* L); }
GameHelp.cpp
#define GAME_HELP_API #include "GameHelp.h" static int mi2[] = { 0x80000000,0x40000000,0x20000000,0x10000000, 0x08000000,0x04000000,0x02000000,0x01000000, 0x00800000,0x00400000,0x00200000,0x00100000, 0x00080000,0x00040000,0x00020000,0x00010000, 0x00008000,0x00004000,0x00002000,0x00001000, 0x00000800,0x00000400,0x00000200,0x00000100, 0x00000080,0x00000040,0x00000020,0x00000010, 0x00000008,0x00000004,0x00000002,0x00000001, }; int fastPow(lua_State *L) { double v_num = lua_tonumber(L, -2);//第一个参数 int v_index = lua_tonumber(L, -1);//第二个参数 double rst = 1.0; int neg = v_index & 0x80000000; v_index = v_index > 0 ? v_index : -v_index; int i; for (i = 0; i < 32; i++) { if (v_index & mi2[i]) { rst = rst * rst * v_num; } else { rst = rst * rst; } } if (neg) rst = 1 / rst; lua_pushnumber(L, rst); return 1; }
lua调用代码
local path = "cppLibForLua.dll" local fastPow = package.loadlib(path,"fastPow") local rst = fastPow(2,5) print("2^5 = "..rst)
任务完成~~~
时间: 2024-10-13 01:08:44