New DLL empty Win32 project, new Test.cpp file, the content is as follows
/*lua call C + + functions/libraries (dynamic link mode) */#include <iostream>using namespace std; #include <lua.hpp>static int Math_abs ( Lua_state *l) { lua_pushnumber (L, ABS ((int) Lual_checknumber (l, 1))); return 1;} static int Math_cos (Lua_state *l) { lua_pushnumber (l, cos ((double) Lual_checknumber (L, 1))); return 1;} static int Math_sin (Lua_state *l) { lua_pushnumber (l, sin (double) lual_checknumber (L, 1)); return 1;} static const Lual_reg Mathlib[] = {{" abs", Math_abs}, {"cos", Math_cos}, { "sin", math_sin}, {NULL, NULL}};//dll is exported through the function Luai_openlib, and LUA uses the Package.loadlib import library function extern "C" __declspec (dllexport) int Luaapidll (lua_state * L)//Where attention is required, this function is named consistent with the library name { luai_openlib (L, "Dy_math", mathlib,0); return 1;}
Lualoadlib.lua file
--region lualoadlib.lualocal libpath= "./. /debug/luaapidll.dll "Local loadlibfunc=package.loadlib (Libpath," Luaapidll ") Loadlibfunc () function COS (a) Print ("Called COS in Lua script") return Dy_math.cos (a) endfunction sin (a) print ("called SIN in Lua script") Return Dy_math.sin (a) EndPrint (COS (60*3.1415926/180)) print (sin ()) os.execute ("pause")--double-click the file directly, The cmd window does not disappear--endregion
Double-click the Lualoadlib.lua file directly and the result is as follows
[Lua] LUA calls C/C + + functions/libraries (dynamic link mode)