LuaJIT ffi Bindings

I am wanting to use LuaJIT and it’s awesome ffi extension. Basically LuaJIT can bind to any exposed C function symbol in a binary.

So in C you can declare a function as such:



extern "C" __declspec(dllexport) void TestFunction();


The lua code to call this is really straight forward:



local ffi = require("ffi")

--The C function prototype.
ffi.cdef
void TestFunction();
]]

--Call the Function
ffi.C.TestFunction()


It’s pretty awesome. The Lua → C calling overhead is basically the same as a C → C call.

I’ve worked out the module loading system and have LuaJIT linked in to my Game module, and can all and run lua code.

The problem is, ffi only searches for symbols in the executable by default. It needs to load my game dll to search it for symbols (this is done on windows with the LoadLibrary function behind the scenes). As the Compile function within the UEEditor rebuilds and hot loads your game dll with a random suffice this is a bit of a problem. The lua code becomes something like this:



local ffi = require("ffi")

ffi.cdef
void TestFunction();
]]

local gameLib = ffi.load("UE4Editor-AutomationGame-5749.dll")

gameLib.TestFunction()


So I need to get the currently used Game dll. Delving through and debugging the UBT, this suffix is appending quite late in the process. So there is no elegant way to getting the dll name and doing a bit of a hack where after the build it spits out the dll name in a file to lua to load. Lua has no native functions for file navigation.

Another option, is I may be able to use ffi to call the various windows native FindFirstFile, FindNextFile etc and find the newest dll to load. But that is also a hack.

So ultimately I need to edit the Engines source to get the dll name out via a simple C function that ffi can bind to. Does anyone know where about the LoadLibrary is called for your game?

Any other thoughts or options on this? Cheers.

Sounds very interesting! I am trying to incorporate my Python knowledge into scripting for UE. Not sure how that will work out.

Why are you trying to create the bindings in Lua instead of using the Lua API to create the bindings from C++?

Probably not very well. You’ll create incredible complexity for yourself for little benefit. There is a reason Epic ditched UnrealScript.

I want to utilise the inherent advantage of LuaJIT and it’s foreign function interface. As stated it has a low overhead and it’s pretty straight forward to implement. Just expose the C functions you want to call from lua and you are done. None of the lua stack C api fun.

Anyway, I got the issue solved here: LuaJIT FFI Binding issue - Programming & Scripting - Epic Developer Community Forums
Was pretty straight forward in the end.

3 Likes