lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Tuesday 22, David Manura wrote:
> 
>   ffi.cdef [[ void swap(double, double, double*, double*); ]]
>   function swap(x,y)
>     local t = ffi.new'double[2]' -- warning: memory alloc not hoisted
>     ffi.C.swap(x,y, t,t+1)
>     return t[0], t[1]
>   end

You could try to use a temp. value allocated outside the function:

ffi.cdef [[ void swap(double, double, double*, double*); ]]
local tmp = ffi.new'double[2]' -- allocate one instance and re-use
function swap(x,y)
  ffi.C.swap(x,y, tmp, tmp+1)
  return tmp[0], tmp[1]
end

As long as the C function doesn't store a reference to those pointers for 
later use, it should be safe (If you are careful).

In the ZeroMQ FFI-based bindings I had a similar problem with a temp. message 
structure needing an allocate (in the C bindings the structure is stack 
allocated not heap allocated).

It would be nice if FFI provided a way to 'stack' allocate a cdata (i.e. mark 
it as only valid for the current scope).  I would think this should make it 
easier for LuaJIT to hoist the alloc.

ffi.cdef [[ void swap(double, double, double*, double*); ]]
function swap(x,y)
  local tmp = ffi.stack'double[2]' -- stack allocate temp. variable.
  ffi.C.swap(x,y, tmp, tmp+1)
  return tmp[0], tmp[1]
end

-- 
Robert G. Jakabosky