Re: FFI newby question: importing C functions

  • From: QuentinC <webmaster@xxxxxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Tue, 26 Jun 2012 11:03:09 +0200

> You can export functions from your main executable.
I don't use mingw, but Windows SDK/DDK and by just having a certain function marked __declspec(dllexport) would put as export in the executable.
Then you should be able to refer it from there.


Yes, it works that way. Thank you !

For info, here's the C code :
double __declspec(dllexport) round2 (double a) {
return round(a);
}

And the lua code, which I also used to compare the pure lua version originally given by Mike against the imported function above :

function math.round(n,p)
if type(p)~='number' then p=0 end
p = 10^p
  if n >= 0 then return math.floor(n*p+0.5)/p
else return math.ceil(p*n-0.5)/p
end end

local n = 100000000
local ffi = require 'ffi'

ffi.cdef[[ int GetModuleFileNameA (void*, char*, int); ]]
local buffer = ffi.new('char[?]', 261)
local length = ffi.C.GetModuleFileNameA(nil, buffer, 260)
local selfExe = ffi.string(buffer, length)

ffi.cdef[[ double round2 (double) ; ]]
local exe = ffi.load(selfExe)

local t = os.clock()
for i=1,n do exe.round2(i/100) end
t = os.clock() -t
print(t)

t = os.clock()
for i=1,n do math.round(i/100) end
t = os.clock() -t
print(t)


The pure lua version, even with the addition of the precision parameter absent from the C version, looks 2.5 to 3 times faster to me (2.4 GHz dual core => 2.15 vs 0.86). The type check is incredibely fast, where standard lua 5.1.4 is very slow (because it does an actual string compare). Conclusion, first try a pure lua version for something so simple that you can do, and keep FFI only where it is really useful.

I didn't know that I could export functions within an executable, I though that it was only reserved to DLLs. I have learned something.
Many thanks to all those helped in this topic.


Other related posts: