大家都知道lua和c++之间可以相互调用;方法有好多调用tolua++.exe,swig 转化工具都行,下面演示一个lua 调用c++dll简单案例: 配置环境: vs2012,lua工程文件和tolua工程文件,lua 安装环境 1,新建一个工程project命名为CameraTest1,添加头文件cameraTest_function.h和cameraTest_function.cpp文件,写入自己想要实现的函数功能,
cameraTest_function.h
bool InitCamera(const char* cameraIp); bool SetCameraReady(const char* saveImagePath, int timeOut); bool GetCaptureStatus(); bool CloseCamera(const char* cameraIp);cameraTest_function.cpp
#include "CameraTest1_function.h" //#include "CameraDLL.h" #include "stdio.h" #include "stdlib.h" #include "string.h" bool InitCamera(const char* cameraIp){ printf("for lua InitCamera success"); char ip[100] = {}; strncpy_s(ip, cameraIp, 100); //IAInitCamera(ip); return true; } bool SetCameraReady(const char* saveImagePath, int timeOut){ printf("for lua SetCameraReady success"); char path[100] = {}; strncpy_s(path, saveImagePath, 100); //IASetCameraReady(path, timeOut); return true; } bool GetCaptureStatus(){ printf("for lua GetCaptureStatus success"); return true; } bool CloseCamera(const char* cameraIp){ printf("for lua CloseCamera success"); char ip[100] = {}; strncpy_s(ip, cameraIp, 100); //IACloseCamera(ip); return true; }2,定义lua接口文件,如下: 新建interface.h 和interface.cpp文件 interface.h
#include <stdio.h> #include "lua.hpp" extern "C" __declspec(dllexport) int __cdecl luaopen_CameraTest1(lua_State * L);interface.cpp
#include "interface.h" int tolua_global_open(lua_State* tolua_S); int __cdecl luaopen_CameraTest1(lua_State * L) { printf("< Load CameraTest1 > ...\r\n"); tolua_global_open(L); printf("< Load CameraTest1 > Finished\r\n"); return 0; }到这一步骤,可能会提示有错误,没有找到lua.hpp文件。 原因没有把lua 和tolua++工程文件添加进来。 在解决方案中添加这两个工程文件后
3,封装函数接口,添加一个后缀名为.pkg 文件,如下: global.pkg,然后把头文件cameraTest_function.h的内容复制过来。$#include 解释一下,tolua++ 根据这个头文件来为其中的每个函数生成胶水函数于一个c文件中,由于胶水函数需要调用原来的函数,所以生成的c文件中包涵cameraTest_function.h这个文件。
$#include "CameraTest1_function.h" bool InitCamera(const char* cameraIp); bool SetCameraReady(const char* saveImagePath, int timeOut); bool GetCaptureStatus(); bool CloseCamera(const char* cameraIp);4,添加批处理文件global.bat 这是为了通过cmd编译转化为lua可用方式文件,如下:
#tolua = C:\lua\bin\tolua++.exe tolua++.exe -o global_lua.cpp global.pkg第一句话是索引出tolua++.exe 文件的地址‘ 第二句话调用tolua++.exe 命令 将global.pkg 转化为global_lua.cpp ,方便lua 调用函数 5, global_lua.cpp 这个文件是通过编译生成的。
方式: tolua++.exe -o global_lua.cpp global.pkg
6,lua 开始调用
定义一个cameratest.lua
package.cpath = package.path..";".."C:\\Users\\Young_liu\\Desktop\\dllexample\\project\\lua-dll-dll\\CameraTest1\\Debug\\?.dll" require "CameraTest1" print(">>",GetCaptureStatus()) print(">>",InitCamera("32")); print(">>",SetCameraReady("Desktop",1)); print(">>",CloseCamera("CloseCamera"));然后终端之行调用lua.exe
编译结果:
整体的一个过程大概如此
完整代码: https://github.com/FlowWaterMe/lua_call_cplusplus-dll