LuaJIT FFI load dll error

2019-07-05 05:32发布

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.

标签: c lua ffi luajit
1条回答
不美不萌又怎样
2楼-- · 2019-07-05 06:23

According to this, there should be declaration of the C function before loading the dll:

local ffi =require("ffi")
ffi.cdef[[
   int add(int a, int b)
]]
local test=ffi.load("C:\\users\\quebe\\Desktop\\add")

addendum:

Additionally, as Egor Skriptunoff mentioned, functions inside the dll file should be declared as exported. The specifics are given in this SO answer.

查看更多
登录 后发表回答