.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