Next: , Previous: , Up: Top  


3 Alien Data

A C data structure is represented by an alien containing the data structure’s memory address. “Peek” primitives are available to read pointers and the basic C types (e.g. ints, floats) at small (fixnum) offsets from an alien’s address. They return to Scheme an alien address, integer or flonum as appropriate. “Poke” primitives do the reverse, storing pointers, integers or floats at fixnum offsets from alien addresses. Other procedures on aliens are alien?, alien-null?, alien-null!, copy-alien, alien=?, alien-byte-increment, and c-peek-cstring. Refer to ffi.pkg in The Source for a complete list.

The C-> and C->= syntaxes apply the peek and poke primitives to constant offsets. They expect their first argument subform to be a constant string — space-separated words naming a C type and any member to be accessed. A member within a struct or union member is specified by appending its name. For example "struct _GdkEvent any window" would specify a peek at the window member of the any member of the struct _GdkEvent data at some alien address. Note that the final member’s type must be a basic C type, pointer type, or enum type. Otherwise, an error is signaled at syntax time.

(C-> alien "struct _GdkEvent any window" window-alien)
→
(#[primitive c-peek-pointer] alien 0 window-alien)
 => #[alien 44 (* GdkWindow) 0x081afc60]

Note that in the example above, the final member has a pointer type. In this case an extra alien argument can be provided to receive the peeked pointer. Otherwise a new alien is created and returned.

Malloc

The malloc procedure returns an alien that will automatically free the malloced memory when it is garbage collected. It can also be explicitly freed with the free procedure. The alien address can be incremented to scan the malloced memory, then freed (without returning it to the original, malloced address). A band restore marks all malloced aliens as though they have been freed.

(free (malloc '|GdkRectangle|))

Next: , Previous: , Up: Top