Standard Library · ffi
class Callback
A Leviathan function made callable from C, returned by ffi::callback.
since 0.1.0-alpha.1linuxwindowswasm
Overview
Pass it where a foreign function expects a function pointer, or pass fn where C wants a raw address. Each callback holds one of a limited number of slots for its signature until it is closed, so close it when C no longer needs it, for example with a using declaration.
Examples
A callback for qsort
uses ffi;
use ffi;
use io::console;
@extern("c")
void qsort(Block base, int nmemb, int size, (Ptr, Ptr) => int32 compar);
void main() {
Block data = Block(8);
data.setInt32(0, 9);
data.setInt32(4, 3);
Callback cmp = ffi::callback::<(Ptr, Ptr) => int32>((Ptr a, Ptr b) => {
int x = ffi::view(a, 4).int32At(0);
int y = ffi::view(b, 4).int32At(0);
return x < y ? -1 : (x > y ? 1 : 0);
});
qsort(data, 2, 4, cmp);
console.writeln(data.int32At(0));
cmp.close();
}
main();
3
Fields
fn
Ptr fnThe C function pointer.
live
bool liveWhether the slot is still held.
sig
int sigThe index of the callback's signature in the program's signature table.
slot
int slotThe slot the callback occupies.
Methods
close
close() -> voidReleases the slot and the Leviathan function it holds.
Calling it again does nothing. C must not call the function pointer afterwards.
Examples
Closing twice
uses ffi;
use ffi;
use io::console;
void main() {
Callback cb = ffi::callback::<(int32) => int32>((int32 x) => x + 1);
console.writeln(cb.live);
cb.close();
cb.close();
console.writeln(cb.live);
}
main();
true
false