Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a pointer to LuaJIT ffi to be used as out argument?

Tags:

lua

ffi

luajit

Assuming there is following C code:

struct Foo { int dummy; }
int tryToAllocateFoo(Foo ** dest);

...How to do following in LuaJIT?

Foo * pFoo = NULL;
tryToAllocateFoo(&pFoo);
like image 860
Alexander Gladysh Avatar asked Dec 23 '12 14:12

Alexander Gladysh


People also ask

How does LuaJIT FFI work?

The LuaJIT FFI automatically generates special callback functions whenever a Lua function is converted to a C function pointer. This associates the generated callback function pointer with the C type of the function pointer and the Lua function object (closure).

What is LUA FFI?

The FFI library allows you to create and access C data structures. Of course, the main use for this is for interfacing with C functions. But they can be used stand-alone, too. Lua is built upon high-level data types. They are flexible, extensible and dynamic.


1 Answers

local ffi = require 'ffi'

ffi.cdef [[
  struct Foo { int dummy; };
  int tryToAllocateFoo(Foo ** dest);
]]

local theDll = ffi.load(dllName)

local pFoo = ffi.new 'struct Foo *[1]'
local ok = theDll.tryToAllocateFoo(pFoo)

if ok == 0 then -- Assuming it returns 0 on success
  print('dummy ==', pFoo[0].dummy)
end
like image 164
finnw Avatar answered Sep 21 '22 12:09

finnw