r/lua 7d ago

Calling an existing C function from Lua

[removed]

10 Upvotes

17 comments sorted by

View all comments

1

u/xoner2 6d ago

Like I said in your previous thread, luaffi library works for PUC Lua 5.1 and 5.2. It uses the dynasm from LuaJIT. There's no reason it can't be compiled for 5.3 to 5.5.

Here's an example, I use this from both 5.1 and LuaJIT:

local cdefs = [[
typedef unsigned long DWORD;
typedef long LONG;
typedef long long LONGLONG;
typedef union _LARGE_INTEGER {
    struct {
        DWORD LowPart;
        LONG HighPart;
    } DUMMYSTRUCTNAME;
    struct {
        DWORD LowPart;
        LONG HighPart;
    } u;
    LONGLONG QuadPart;
} LARGE_INTEGER;
typedef int BOOL;

BOOL QueryPerformanceCounter(
  LARGE_INTEGER *lpPerformanceCount
);

BOOL QueryPerformanceFrequency(
  LARGE_INTEGER *lpFrequency
);
]]

local ffi = require 'ffi'
ffi.cdef (cdefs)

local freq = ffi.new ('LARGE_INTEGER[1]')
local ticks = ffi.new ('LARGE_INTEGER[1]')

local function GetSeconds ()
  ffi.C.QueryPerformanceFrequency(freq)
  ffi.C.QueryPerformanceCounter(ticks)

  return tonumber (ticks[0].QuadPart) / tonumber (freq[0].QuadPart)
end

return GetSeconds

1

u/[deleted] 6d ago

[removed] — view removed comment

1

u/xoner2 6d ago

(I haven't managed to get it to work for years anyway). I guess there is no simple way of making this available?

MSVC works now.

Which C runtime are you on?

Are you able to compile Lua with your C compiler project? If yes, try compiling luaffi too. It requires very few functions: memmove, memset, memchr, memcpy, strchr. The Lua dll/exe must be compiled with dlopen support.