closure#
עטיפת coderef של Perl כמצביע פונקציה שניתן לקרוא לו מ־C.
תקציר#
# 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$queueand returns at once, and the sub runs when Perl takes the queue’s events. It takes noP, an address valid only during the call, and returnsv, a number,boro.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.
אורך חיים#
ה־closure נשאר חי עד שקוראים ל־closure_free עם הכתובת שהפונקציה הזו החזירה. שחרורו בזמן ש־C עדיין מחזיקה את המצביע משאיר את הספרייה ההיא קוראת לזיכרון משוחרר, ולכן יש לשחרר אותו רק לאחר שצד ה־C קיבל הוראה להפסיק - עבור driver, פירוש הדבר לקשור אותו לידית ולשחרר אותו בעת הניתוק.
שגיאות ב־callback#
callback שעושה die אינו מפעפע את השגיאה: השגיאה הייתה צריכה להתפרק דרך מסגרת המחסנית של הקורא ב־C. $@ מוצב וה־closure מחזיר אפס מטיפוס ההחזרה המוצהר שלו; יש לבדוק את $@ אחרי קריאת ה־C שהפעילה אותו.