closure#

Wrap a Perl coderef as a C-callable function pointer.

Synopsis#

# 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.

Options#

  • queue => $queue - a queued closure, which C may call on any thread: each call copies its arguments into the Peta::FFI::Queue $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.

Lifetime#

The closure stays alive until closure_free is called with the address this returned. Freeing it while C still holds the pointer leaves that library calling into released memory, so free it only after the C side has been told to stop - for a driver, that means tying it to the handle and releasing it at disconnect.

Errors in the callback#

A callback that dies does NOT propagate: the error would have to unwind through the C caller’s stack frame. $@ is set and the closure returns a zero of its declared return type; check $@ after the C call that triggered it.