lua加载DLL

.cpp

 

//若没有在项目属性--库文件、依赖文件、包含添加。则添加一下路径

#pragma  comment (lib,"lua5.1.lib")

 

#include "stdafx.h"

#include "lua.hpp"

 

extern "C" {

#include "lua.h" 

#include "lualib.h" 

#include "lauxlib.h" 

}

 

static int MyLuaDLL_HelloWorld(lua_State* L)

{

      MessageBoxA(NULL,"Hello","World",MB_OK);

      return 0;

}

 

static int MyLuaDLL_average(lua_State *L)

{

      int n = lua_gettop(L);

      double sum = 0;

      int i;

      for (i = 1; i <= n; i++)

      {

           sum += lua_tonumber(L, i);

      }

      lua_pushnumber(L, sum / n);

      lua_pushnumber(L, sum);

      //2代表返回2个参数

      return 2;

}

 

//当lua使用MyLuaDLL.HelloWorld时,响应函数MyLuaDLL_HelloWorld

static const luaL_reg MyLuaDLLFunctions [] =

{

      {"HelloWorld",MyLuaDLL_HelloWorld},

      {"average",MyLuaDLL_average},

      {NULL,NULL}

};

 

/*此处导出函数luaopen_MyLuaDLL。其中MyLuaDLL要与.exe程序名一致

  若lua用dofile调用dll必须一致,若lua用loadlib加载dll可不一致

  luaL_register(L, "MyLuaDLL", MyLuaDLLFunctions); 中的MyLuaDLL,用于给lua调用DLL中的函数,类似外放对象。

*/

extern "C"  __declspec(dllexport) int luaopen_MyLuaDLL(lua_State* L)

{

      luaL_register(L, "MyLuaDLL", MyLuaDLLFunctions);

      return 1;

}

 

BOOL APIENTRY DllMain( HMODULE hModule,

                       DWORD  ul_reason_for_call,

                       LPVOID lpReserved

                             )

{

      switch (ul_reason_for_call)

      {

      case DLL_PROCESS_ATTACH:

           //printf("Process attach. \n");

           break;

      case DLL_PROCESS_DETACH:

           //printf("Process detach. \n");

           break;

      case DLL_THREAD_ATTACH:

           //printf("Thread attach. \n");

           break;

      case DLL_THREAD_DETACH:

           //printf("Thread detach. \n");

           break;

      }

      return (TRUE);

}

 

 

.lua

--Lua_Dll.dll必须放在luajit同一目录下

local testlib = package.loadlib("Lua_Dll.dll","luaopen_MyLuaDLL");   --获取DLL中抛出函数地址

print (testlib)

if(testlib)then

    testlib();  --调用DLL中抛出函数

else

    -- Error

end

 

MyLuaDLL.HelloWorld();

 

a,b=MyLuaDLL.average(23,33,3344);

print("average:",a,"sum:",b);

 

转载于:https://www.cnblogs.com/gd-luojialin/p/10962878.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值