lua加载DLL

Posted gd-luojialin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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);

 

以上是关于lua加载DLL的主要内容,如果未能解决你的问题,请参考以下文章

LUA 如何调用DLL插件啊。

lua调用失败是啥意思

lua分页加载

通过相对路径加载 Lua 文件

lua State加载部分库

Lua 错误加载模块 'libpng' (Torch, MacOSX)