LuaJIT FFI load dll error

Viewed 2055

I want to code some functions in C to use in Lua and the easiest way to do this I think I can find is using LuaJIT's FFI.

I have a C file "add.c":

int add(int a, int b){
return a+b;
}

I assemble it into "add.o" with:

gcc -c add.c

I make "add.dll":

gcc - shared -o add.dll add.o

Finally, I try to run the following Lua code in LuaJIT:

local ffi =require("ffi")

local test=ffi.load("C:\\users\\quebe\\Desktop\\add")

ffi.cdef[[
int add(int a,int b);
]]

print(test.add(1,2))

and get:

luajit: test.lua:3: cannot load module 'C:\users\quebe\Desktop\add': %1 is 
not a valid Win32 application.

stack traceback:
    [C]: in function 'load'
    test.lua:3: in main chunk
    [C]: at 0x7ff72be120c0

but I have no idea how to interpret this to debug.

3 Answers

This sounds like the dll you are trying to load has dependency dll's that cant be loaded - usually because they arent in Windows search path.

Ideas for solving:

  • Grab dependency walker and look at your dll - missing ones are usually marked red.
  • Often if you build with Visual Studio you may need visual studio runtimes like vcp140.dll and vcr140.dll (or similar). These are sometimes not correctly registered, and you may need to do that.
  • On Windows you must make sure that when you build the dll, all functions are exported (this can be done in a couple of ways - see MSVC help) and that they have __stdcall or __cdecl name mangling. Without this, you wont be able to call the functions using ffi.
  • Finally, watch out for security disabling of dlls. Sometimes dlls will be marked as not usable by the Win10 system. Check the properties and enable the dll. This usually happens when copying a dll between certain types of folders.

I had the same error while trying to do something related, turns out the LuaJIT binary was compiled in 64 bits and the .dll I was trying to load was compiled in 32 bits.

Related