# closure Τυλίγει ένα coderef της Perl ως δείκτη συνάρτησης που μπορεί να κληθεί από τη C. ## Σύνοψη ```perl # int (*)(void*) - a progress handler my $ptr = Peta::FFI::closure('(o)i', sub { my ($ud) = @_; 0 }); Peta::FFI::call($lib, 'sqlite3_progress_handler', '(oioo)v', $db, 100, $ptr, undef); ... Peta::FFI::closure_free($ptr); ``` The signature grammar is `call`’s. A closure takes and returns the numbers, `o`, `p`, `P`, `b` and records - `{Class}` by value, and as an argument `*{Class}` by pointer, which the callback gets as a read-only copy. As an argument it also takes what C lends with its length in another argument: `&P[#k]` bytes, as a string, and `&T[#k]` numbers or `o`, as an array reference - `(o&P[#3]L)v` is a callback handed `void *data, size_t len`. There is no `;`, `s`, handle type, other array, pointer to a number, long double or complex number: C calls the closure through a fixed prototype and owns nothing it hands over. The returned value is the raw address of the trampoline, to be passed wherever C wants the function pointer. ## Επιλογές - `queue => $queue` - a queued closure, which C may call on any thread: each call copies its arguments into the [Peta::FFI::Queue](Queue.md) `$queue` and returns at once, and the sub runs when Perl takes the queue’s events. It takes no `P`, an address valid only during the call, and returns `v`, a number, `b` or `o`. - `returns => $value` - what a queued closure returns to C, read once, here; 0 when not given. ## Threads A closure may be called only on the interpreter’s own thread, during a C call Perl made - a progress handler, a comparator, a visitor. A library that calls it from a thread of its own stops the process with a message saying so, since Perl cannot run there. A library that calls back on its own threads takes a queued closure instead, and events a library queues itself reach Perl through a file descriptor the event loop watches, as a [Peta::FFI::EventSource](EventSource.md). ## Διάρκεια ζωής Το closure παραμένει ζωντανό μέχρι να κληθεί η `closure_free` με τη διεύθυνση που επέστρεψε αυτή. Η απελευθέρωσή του όσο η C κρατά ακόμη τον δείκτη αφήνει εκείνη τη βιβλιοθήκη να καλεί σε απελευθερωμένη μνήμη, οπότε απελευθερώστε το μόνο αφού ειπωθεί στην πλευρά της C να σταματήσει - για έναν οδηγό, αυτό σημαίνει να το δέσετε με τον χειριστή και να το απελευθερώσετε κατά την αποσύνδεση. ## Σφάλματα στο callback Ένα callback που τερματίζει με die ΔΕΝ διαδίδει το σφάλμα: το σφάλμα θα έπρεπε να ξετυλιχτεί μέσα από το πλαίσιο στοίβας του καλούντος C. Ορίζεται το `$@` και το closure επιστρέφει ένα μηδενικό του δηλωμένου τύπου επιστροφής του· ελέγξτε το `$@` μετά την κλήση C που το ενεργοποίησε.