programmer
programmer

Reputation: 602

Loading .dll in Lua using require(..) or dofile(..)

Is it possible to load .dll library inside of Lua? Say I have a compiled .dll file and the folder looks like this:

<folder>
   |------test.lua
   |------mylib.dll

Can I use the .dll library inside of lua using require(..) or dofile(..)?

Also does the .dll have to be in some format? If so can you share the template of the C code which I can compile to lua recognizable .dll

Thanks!

Upvotes: 2

Views: 13678

Answers (2)

Chris
Chris

Reputation: 2763

You have a few choices here depending on what you want to do. Lua's "require" will load the DLL and will expect a single function to be present:

int luaopen_XXXXX (lua_State* L)

The DLL must be named to match the "XXXXX" part, so if you wrote a module called "sprite.dll" then you need to create a function called luaopen_sprite.

From inside this function, you can manually register 'C' functions with the Lua 'C' API, which allows them to be called from your script(s). See Lua docs for this.

You could also use a wrapping tool. I have used SWIG extensively. It automatically takes header files and builds a C or C++ file which contains all the above.

Using FFI (foreign function interface) is also possible. Its a way of directly calling C interfaces, which it does I believe using low-level processor specific stack construction and jmps/calls.

Upvotes: 3

Oliver
Oliver

Reputation: 29591

If the .DLL is not a Lua extension module but just a generic .DLL, then you can use an "FFI" library like luaffi to load it and call the functions in it.

Upvotes: 0

Related Questions