views:

233

answers:

3

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?

+2  A: 

Try Alien: http://alien.luaforge.net/

There is also C/Invoke: http://www.nongnu.org/cinvoke/lua.html

Alexander Gladysh
Note that alien is already included in the Lua for Windows release.
RBerteig
+2  A: 

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.

RBerteig
A: 

You will have to use either an automated tool, or written by hand, a C++ interface. Lua can't handle straight C++ code.

DeadMG