lua调用dll demo

使用的是lua5.3

DllMain.cpp

 1 //生成的dll  是   lua_add53.dll
 2 //luaopen_lua_add
 3 extern "C" {
 4 #include "F:/lua_src/lua-5.3.5_Win64_vc15_lib/include/lua.h"  
 5 #include "F:/lua_src/lua-5.3.5_Win64_vc15_lib/include/lualib.h"  
 6 #include "F:/lua_src/lua-5.3.5_Win64_vc15_lib/include/lauxlib.h"
 7 };
 8 #pragma comment(lib, "F:/lua_src/lua-5.3.5_Win64_vc15_lib/lua53.lib")
 9 
10 #include <iostream>  
11 using namespace std;
12 
13 extern "C" int ShowMsg(lua_State* luaEnv) {
14   cout << "Hello world from clibs!" << endl;
15   return 0; // 返回值个数为0个.  
16 }
17 
18 extern "C" int sub2(lua_State* L)
19 {
20   double op1 = luaL_checknumber(L, 1);
21   double op2 = luaL_checknumber(L, 2);
22   int temp = op1 - op2;
23   lua_pushnumber(L, temp);
24   return 1;
25 }
26 
27 // part one: 要导出的函数列表
28 static luaL_Reg luaLibs[] = {
29     { "ShowMsg", ShowMsg},
30     { "sub2", sub2},
31     { NULL, NULL }
32 };
33 
34 // part two: DLL入口函数,Lua调用此DLL的入口函数.  
35 extern "C" __declspec(dllexport)
36 int luaopen_lua_add(lua_State* luaEnv) {   //WinFeature是modole名, 将来require这个名字
37   //lua_register(luaEnv, "ShowMsg", ShowMsg);  //关键一行, 在luaState上注册好这个lib
38   //lua_register(luaEnv, "sub2", sub2);  //关键一行, 在luaState上注册好这个lib
39   lua_newtable(luaEnv);
40   luaL_setfuncs(luaEnv, luaLibs,0);
41   return 1;
42 }

编译后是 lua_add53.dll

lua

1 local mytest = require "lua_add"
2 mytest.ShowMsg();
3 print(mytest.sub2(1,2));

 

posted @ 2019-08-16 18:00  ff_d  阅读(1878)  评论(0编辑  收藏  举报