如何从Lua调用C ++ DLL内的函数? [英] How do I call functions inside C++ DLL from Lua?

查看:151
本文介绍了如何从Lua调用C ++ DLL内的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用C ++编写的DLL,它是旧的代码,不能修改源代码。我想要从 Lua 。



例如,我想做这样的事情:

   - 我的Lua文件
include(myCppDll.dll)

函数callCppFunctionFromDll()
local result = myCppFunctionFromDll(arg1,arg2)
- 结果这里
end

这样可能吗?

解决方案

如果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.

这篇关于如何从Lua调用C ++ DLL内的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆