Next: , Previous: , Up: FFI  


4 Alien Functions

The C-call syntax produces code that applies call-alien to an alien function structure — a cache for the callout trampoline’s entry address.

(C-call "gtk_button_new" (make-alien '(* |GtkWidget|)))
→
(call-alien '#[alien-function gtk_button_new] (make-alien …))

The alien function contains all the information needed to load the callout trampoline on demand (i.e. its name and library). Once the alien function has cached the entry address, call-alien can invoke the trampoline (via #[primitive c-call]). The trampoline gets its arguments off the Scheme stack, converts them to C values, calls the C function, conses a result, and returns it to Scheme.

A function returning a pointer type is treated specially. Its trampoline expects an extra (first) argument. If the argument is #f, the return value is ignored. If the argument is an alien, the function’s return value clobbers the alien’s address. This makes it easy to grab pointers to toolkit resources without dropping them, and to avoid unnecessary consing of aliens.

A function returning a struct or union type is treated similarly. Its trampoline expects an extra (first) argument. If the argument is #f, the return value is ignored. If the argument is an alien, the returned struct or union is copied to that address.

Struct and union type parameters of a function are treated similarly. The function’s trampoline expects an alien argument for each such parameter and copies the struct or union from the argument address into a local variable. Callbacks currently cannot receive struct or union type arguments, though they can receive pointer type arguments (consing an alien for each).

The alien-function structures are fasdumpable. The caching mechanism invalidates the cache when a band is restored, or a fasdumped object is fasloaded. The alien function will lookup the trampoline entry point again on demand.


Next: Callbacks, Previous: Alien Data, Up: FFI