lua-users home
lua-l archive

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

Hi all,

I've got a small problem with ffi.gc and I don't really understand the
problem. Here what I'm doing

I'm using ffi.cdef for the following struct/functions:

typedef struct
  size_t size;
  size_t *data;
} gsl_permutation;

gsl_permutation *gsl_permutation_calloc (const size_t n);
void gsl_permutation_init (gsl_permutation * p);
void gsl_permutation_free (gsl_permutation * p);

The function "gsl_permutation_calloc" does return a properly
initialized object and the corresponding "free" function deallocate
the memory for the "data" array and the object itself.

So far this is pretty much straightforward, this is just plain C. Then
I do the following in LuaJIT2

p = ffi.C.gsl_permutation_calloc(5)
ffi.gc(p, ffi.C.gsl_permutation_free)

where p is actually a local variable. The problem is that in this case
I can get memory corruption and it seems that it happens when p is
garbage-collected. I don't understand why... I'm doing something wrong

The following variant seems to work:

p ='gsl_permutation[1]')
local data ='size_t[%i]', nr))
p[0].size = nr
p[0].data = data

but in this case there is a problem: luajit is not aware that p
depends on data and so it can collect data when p is still around. I
was able to find a solution by storing the cdata objects in a table
but I'm wondering what is the best method to do that correctly.

Mike, I guess you are the only one that can potentially help me, I
hope you can get a look at that. Unfortunately I'm not able to provide
a simple test case but I can try if you think it is really needed.

Thanks is any case :-)