且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从Lua调用C ++ DLL内的函数?

更新时间:2023-11-24 12:13:04

如果Alien不符合您的需求,如果DLL有一个强大的面向对象的界面,您需要在对象的成员和方法以及只是调用导出的函数,那么你应该看看生成一个将DLL从旧版API连接到Lua的包装器DLL。



可以使用包装器生成器,如 Swig ,它将为Lua以及许多其他脚本语言编写包装基于类和函数的声明,通常是si只需要比现有的.h文件多一点输入。



Lua也是简单的代码,因为在C中手工编写自己的包装可能会更简单。为此,从C中创建Lua可调用模块的标准配方开始,并实现将参数从Lua堆栈转换为适合每个API调用的形式的函数,调用到DLL中,并将任何结果推回到Lua叠加。这也是利用Lua为DLL中不得不使用输出指针来处理第二个(或更多)返回值的函数返回多个结果的功能的地方。 Lua User's Wiki提供了讨论问题和一些示例代码。



还有一个页面专门用于将Lua绑定到其他语言在Lua用户的维基。


I have a DLL written in C++ that is legacy code and cannot modify the source code. I want to be able to call some of the functions inside of the DLL from Lua.

For example, I'd like to do something like this:

-- My Lua File
include(myCppDll.dll)

function callCppFunctionFromDll()
     local result = myCppFunctionFromDll(arg1, arg2)
     --Do something with result here
end

Is something like this possible?

If Alien doesn't meet your needs, and it might not be easy to use if the DLL has a strongly object oriented interface where you need to get at the members and methods of objects as well as just call exported functions, then you should look at generating a wrapper DLL that interfaces the legacy API from the DLL to Lua.

This can be done with a wrapper generator such as Swig which will write wrappers for Lua as well as many other scripting languages based on declarations of classes and functions, often simply taking little more than the existing .h files as input.

Lua is also simple enough code for that it might be simpler to write your own wrapper by hand in C. To do this, start from the standard recipe for creating a Lua callable module in C, and implement functions that transfer arguments from the Lua stack into a form suitable for each API call, call into the DLL, and push any results back on the Lua stack. This is also the place to take advantage of Lua's ability to return more than one result for those functions that in the DLL had to use output pointers to deal with a second (or more) return value. A discussion of the issues and some sample code is available at the Lua User's Wiki.

There is also a page devoted to binding Lua to other languages at the Lua User's Wiki.