lua-users home
lua-l archive

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


2011/4/15 Mike Pall <mikelu-1104@mike.de>:
> The __gc metamethod only applies to structs that are allocated
> with ffi.new(). It never applies to pointers or refs. It's most
> useful to release resources _associated_ with a struct (e.g.
> interior pointers to malloc()'ed memory).
>
> Maybe you're confusing this with ffi.gc(), which is a lower-level
> mechanism. It can be applied to aggregates _or_ pointers/refs.
> It's most useful when the resource to be released comes as a
> pointer from a C function (e.g. a FILE *).
>
>>    local m = gsl_matrix {n1, n2, n2, block.data, block, 1}
>
> Stylistic notice: there's no need to create a temporary table.
> Initializers for structs take multiple arguments.

Mike, thank you very much for the clarifications, you tips are very useful.

>> My problem here is that by calling gsl_matrix_alloc I get a pointer
>> and not a struct instance and so the metatable that I can associate to
>> a 'gsl_matrix' does not apply.
>
> But it does apply. And if you need to automatically free the
> matrix, then attach a finalizer to the pointer with ffi.gc().
> You need to pass the pointer around and keep it alive, of course.
>
> In your case it's probably easiest to declare the C function with
> a reference return value:
>
> ffi.cdef[[
> gsl_matrix &gsl_matrix_alloc(...);
> ]]
>
> ffi.metatype("gsl_matrix", { ... })
>
> function matrix.new(...)
>  return ffi.gc(cgsl.gsl_matrix_alloc(...), cgsl.gsl_matrix_free)
> end

hmmm... return a reference is not ANSI C, this is C++. I guess you
accept it in cdefs as an ad hoc extensions.

By the way, what I retain from your suggestion is that for pointers I
can have problems because the pointer arithmetic/semantic has the
priority and can get in the way. I've also understood the difference
between ffi.gc and the __gc metamethods, before I was confusing them.

I will keed the approach that I've chosen since it seems to be
correct, I will try to work with struct instances instead of pointers.

Thanks again ;-)
-- 
Francesco