lua调用dll 编译lfs

From:http://blog.csdn.net/snlscript/article/details/16340653

#include <Windows.h>

extern "C"{
#include <lua.h>
#include <lauxlib.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <lualib.h>
#include <math.h>
}

static int mysin (lua_State *L)
{
double d = luaL_checknumber(L, 1);
lua_pushnumber(L, sin(d));
return 1;
}

static int l_printf(lua_State *L)
{
const char * pPattern = luaL_checkstring(L, 1);
const char * str = luaL_checkstring(L, 2);
lua_pushnumber(L, printf(pPattern, str));
return 1;
}

static int l_MessageBox(lua_State *L)
{
const char * sTitle = luaL_checkstring(L, 1);
const char * sText = luaL_optstring(L, 2, "");
MessageBox(NULL, sTitle, sText, 0);
return 1;
}

static const struct luaL_Reg mylib[] =
{
{"mysin", mysin},
{"printf", l_printf},
{"messagebox", l_MessageBox},
{NULL, NULL}
};

extern "C" int __declspec(dllexport) luaopen_mylib(lua_State *L)
{
luaL_newlib(L, mylib);
return 1;
}

记得要在属性/连接器/输入/模块定义文件中输入def的文件名称如lfs.def,以及lua的lib(或dll?测试用的lib)

上面的代码中,最后export出去的函数是luaopen_mylib,一定要注意:函数名luaopen_mylib表明了最后输出的dll名称必须为mylib.dll,而且大小写要一致,否则lua无论如何都找不到luaopen_mylib函数的。

上面函数是cpp的,如果是c的最后一个函数格式会有变int luaopen_lfs (lua_State *L) {。。。具体参照luafilesystem的代码

lfs.def内容:

LIBRARY lfs.dll
VERSION 1.6
EXPORTS
luaopen_lfs

原文地址:https://www.cnblogs.com/xiao0913/p/4611153.html