lua-users home
lua-l archive

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

2011/3/15 Mike Pall <>:
> Why do you need to use C calls for that?

Well, the reason is that I've translated the Levenberg-Marquardt
routine for non-linear fit to Lua + FFI so it was much more simple to
use the GSL structure like native GSL matrix, vector and permutations.
Othewise I know that such simple structures like the permutations can
be implemented finely just with plain Lua without FFI.

> Assuming the data part
> doesn't grow after allocation you could use a variable-length
> struct instead:

> ffi.cdef[[
> typedef struct {
>  size_t size;
>  size_t data[?];
> } gsl_permutation;
> ]]
> local p ="gsl_permutation", 5)
> p.size = 5
> This nicely avoids the GC issues, too.

Nice idea but I think that the VLS that you suggest is not compatible
with the original one so I cannot pass it to GSL functions.

> BTW: The use of size_t for anything but actual memory sizes is not
>     a good idea. I guess int32_t would be a much better fit here.

Hmmm... this is not my choice but standard GNU coding practice and GSL
library stick with it. They use systematically int for integers and
size_t for unsigned integer. I don't know why the use size_t instead
of unsigned int but why choose the size of the word with int32_t if
you can just use a native int (unsigned or not) ?

>> p = ffi.C.gsl_permutation_calloc(5)
>> ffi.gc(p, ffi.C.gsl_permutation_free)
> It doesn't make a difference here, but always use it like this:
> local p = ffi.gc(ffi.C.gsl_permutation_calloc(5), 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?
> Either you're dropping the last reference to p too early or
> something is wrong with the deallocation function.

hmmm... I will look better if I can understand better the problem and
may reproduce it with  a simple test case. I don't like to get
segmentation fault here and there... :-/

> Keep it in one combined (variable-length) struct. Or use a plain
> Lua table for more complex linked data structures. It's unlikely
> to make much of a difference, except for big arrays.

Thanks for the help, Mike. I will look better and probably try what yu

Best regards,