方法一
创建VS dll项目
#ifndef CPP_DLL_API_H
#define CPP_DLL_API_H
#ifdef __cplusplus
#define EXTERN_C extern "C"
#else
#define EXTERN_C extern "C"
#endif
#ifndef EXPORT_API
#define EXPORT_API EXTERN_C __declspec(dllexport)
#else
#define EXPORT_API EXTERN_C __declspec(dllimport)
#endif
#endif
#include "cpp_dll_lib_api.h"
extern "C"{
#include <lua.h>
#include <lauxlib.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <lualib.h>
#include <math.h>
}
#include <Windows.h>
EXPORT_API int Add(lua_State *L){
int param_count = lua_gettop(L);
if (param_count != 2) {
lua_pushnil(L);
lua_pushstring(L, "ShowMessageBox: param num error");
return 2;
}
int arg1 = luaL_checknumber(L, 1);
int arg2 = luaL_checknumber(L, 2);
lua_pushnumber(L, arg1 + arg2);
return 1;
}
EXPORT_API int ShowMessageBox(lua_State *L)
{
int param_count = lua_gettop(L);
if (param_count != 2) {
lua_pushnil(L);
lua_pushstring(L, "ShowMessageBox: param num error");
return 2;
}
const char * sTitle = luaL_checkstring(L, 1);
const char * sText = luaL_checkstring(L, 2);
if (sTitle == NULL || strlen(sTitle) == 0 || sText == NULL || strlen(sText) == 0) {
lua_pushnil(L);
lua_pushstring(L, "ShowMessageBox: param error");
return 2;
}
int ret = MessageBoxA(NULL, sTitle, sText, 0);
lua_pushnumber(L, ret);
return 1;
}
Lua脚本
将dll放到lua/clib中
local pf = package.loadlib("cpp_dll_lib.dll","ShowMessageBox")
print(pf)
pf("hello", "again")
dumpbin查看导出函数
dumpbin.exe /exports .\cpp_dll_lib.dll
dumpbin在(不同版本vs不同路径 我这里是vs2013的)
C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin