Lua语言如何调用自己编写的C DLL文件
/*---c code:---*/
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
#include <windows.h>
/*----------定义函数--------------*/
static int MyLuaDLL_HelloWorld(lua_State* L)
{
MessageBox(NULL,"Hello","World",MB_OK);
return 0;
}
static int MyLuaDLL_average(lua_State *L)
{
/* get number of arguments */
int n = lua_gettop(L);
double sum = 0;
int i;
/* loop through each argument */
for (i = 1; i <= n; i++)
{
/* total the arguments */
sum += lua_tonumber(L, i);
}
/* push the average */
lua_pushnumber(L, sum / n);
/* push the sum */
lua_pushnumber(L, sum);
/* return the number of results */
return 2;
}
/*-----------注册函数---------------*/
static const luaL_reg MyLuaDLLFunctions [] =
{
{"HelloWorld",MyLuaDLL_HelloWorld},
{"average",MyLuaDLL_average},
{NULL, NULL}
};
int __cdecl __declspec(dllexport) luaopen_MyLuaDLL(lua_State* L)
{
luaL_openlib(L, "MyLuaDLL", MyLuaDLLFunctions, 0);
return 1;
}
-- lua code: --
local testlib = package.loadlib("Lua_Dll.dll","luaopen_MyLuaDLL");
print (testlib)
if(testlib)then
testlib();
else
-- Error
end
MyLuaDLL.HelloWorld();
a,b=MyLuaDLL.average(23,33,3344);
print("average:",a,"sum:",b);