首先:工具:生成dll用vs2008。
一、首先生成lua库,即(*.lib)库
1、在lua官网上下载lua源代码
2、用vs2008建一个静态库,把lua源代码全加入到工程中,可以把lua.c、luac.c不用放到工程中。编译生成就可以了。
二、生成dll库
1.用vs2008建一个动态库,配置环境:
// folderScan.cpp : 定义 DLL 应用程序的导出函数。 // #include "stdafx.h" //#include <dir.h> #include <string.h> #include <errno.h> #include <stdlib.h> #define LUA_COMPAT_MODULE extern "C" { #include "lua.h" #include "lualib.h" #include "lauxlib.h" }; #include "log.h" #include <windows.h> //#pragma comment(lib,"C:\\Users\\liuweifeng\\Documents\\Visual Studio 2008\\Projects\\folderScan\\lib\\lua5.2.1.lib") #if defined(_WIN32) extern "C" _declspec(dllexport) int luaopen_MyLuaDLL(lua_State* L); #else extern "C" int luaopen_MyLuaDLL(lua_State* L); #endif CLog log; int MyLuaDLL_Dir(lua_State *L) { WIN32_FIND_DATA FindFileData; HANDLE hFind = INVALID_HANDLE_VALUE; char DirSpec[MAX_PATH + 1] = {0};//指定路径 DWORD dwError; const char *path = luaL_checkstring(L,1); const char *desDir = luaL_checkstring(L,2); log.Add(path); log.Add(desDir); strcpy(DirSpec,path); strncat (DirSpec, "\\*", 3); log.Add(DirSpec); hFind = FindFirstFile(DirSpec,&FindFileData); char err[64] = {0}; if (hFind == INVALID_HANDLE_VALUE) { lua_pushnil(L); itoa(GetLastError(),err,10); lua_pushstring(L, err); /* error message */ return 2; } /* create result table */ lua_newtable(L); int i = 1; char sourcePath[MAX_PATH + 1] = {0}; char destPath[MAX_PATH + 1] = {0}; if (FindFileData.dwFileAttributes != FILE_ATTRIBUTE_DIRECTORY ) { lua_pushnumber(L, i++); /* push key */ lua_pushstring(L, FindFileData.cFileName); /* push value */ lua_settable(L, -3); sprintf(sourcePath,"%s\\%s",path,FindFileData.cFileName); sprintf(destPath,"%s\\%s",desDir,FindFileData.cFileName); log.Add(destPath); MoveFile(sourcePath,destPath); } while(FindNextFile(hFind, &FindFileData) != 0) { if (FindFileData.dwFileAttributes != FILE_ATTRIBUTE_DIRECTORY) { lua_pushnumber(L, i++); /* push key */ lua_pushstring(L, FindFileData.cFileName); /* push value */ lua_settable(L, -3); sprintf(sourcePath,"%s\\%s",path,FindFileData.cFileName); sprintf(destPath,"%s\\%s",desDir,FindFileData.cFileName); log.Add(destPath); MoveFile(sourcePath,destPath); } } FindClose(hFind); return 1; } /*-----------注册函数---------------*/ static const struct luaL_Reg MyLuaDLLFunctions [] = { {"myDir",MyLuaDLL_Dir}, {NULL, NULL} }; extern "C" _declspec(dllexport) int luaopen_MyLuaDLL(lua_State* L)//dll接口 { luaL_register (L, "MyLuaDLL", MyLuaDLLFunctions); //luaL_setfuncs (L, MyLuaDLLFunctions,0); //luaL_newlib(L, MyLuaDLLFunctions); //luaL_openlibs(L); return 1; }三、lua调用dll源代码:
--调用外部dll local testlib = package.loadlib("E:/dfproject/imageScan/script/folderScan.dll","luaopen_MyLuaDLL") if testlib then testlib()--必须有这个 LOG("testlib") else LOG("ERROR") end
ImageList = MyLuaDLL.myDir(dirPath,desDirPath) if ImageList then for k,v in pairs(ImageList) do LOG("k = "..k.." v = "..v) end else LOG("DIR ERROR") end我的myDir函数返回的是一个table。