跟著本文, 大家只需要簡單的4個步驟就能build出自己的C/CPP語言DLL庫供Lua require隨意調用.
需要準備的軟件
- Visual Studio 2015/2017
- Lua5.1 source code (click to download)
step1: 建DLL工程
使用VisualStudio2017, 新建一個Win32 Console Application
1
2
step2: 拷lua5.1代碼
創建成功后, 從Lua5.1 source file(百度搜索lua5.1 source file下載)中, 拷貝所有的源代碼.c和.h文件到項目文件夾中. 我們其實有更簡潔的引用lua.lib而不是直接拷貝源代碼的方式, 但是新手入門先用這個方法不容易出錯.
3
拷貝完文件后, 要在Visual Studio IDE中右鍵項目名 --> 添加 --> 現有項目, 選中所有剛才復制的lua5.1源代碼.
step3: 寫DllMain.cpp代碼
新建DllMain.cpp
文件, 寫上如下的代碼. 代碼很簡短, 而且寫好了注釋供大家參考.
extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
};
#include <iostream>
using namespace std;
extern "C" int ShowMsg(lua_State* luaEnv) {
cout << "Hello world from clibs!" << endl;
return 0; // 返回值個數為0個.
}
// part one: 要導出的函數列表
static luaL_Reg luaLibs[] = {
{ "ShowMsg", ShowMsg},
{ NULL, NULL }
};
// part two: DLL入口函數,Lua調用此DLL的入口函數.
extern "C" __declspec(dllexport)
int luaopen_WinFeature(lua_State* luaEnv) { //WinFeature是modole名, 將來require這個名字
const char* const LIBRARY_NAME = "WinFeature"; //這里也寫WinFeature
luaL_register(luaEnv, LIBRARY_NAME, luaLibs); //關鍵一行, 在luaState上注冊好這個lib
return 1;
}
step4: build出dll庫
點擊build --> build solution (ctrl + shift + B)
生成出xxx.dll庫文件.
在項目的Debug文件夾中取出所需的dll庫.
debug文件夾中取出xxx.dll文件
再把這個xxx.dll庫復制到C:\Program Files (x86)\Lua\5.1\clibs
文件夾下即可. (這里路徑名僅供參考, 要以大家的實際lua路徑為準)
extra: 測試是否成功
require "WinFeature"
WinFeature.ShowMsg() -- it should prints "Hello world from clibs!"
cmd結果
顯然, 我們成功了!!!