You are looking at historical revision 17603 of this page. It may differ significantly from its current revision.

C interface

The following functions and macros are available for C code that invokes Scheme or foreign procedures that are called by Scheme:

Temporary stack


[C macro] void C_save (C_word x) :

Saves the Scheme data object x on the temporary stack.


[C macro] void C_restore

Pops and returns the topmost value from the temporary stack.

Constructors for immediate Scheme objects

"immediate" Scheme objects are objects that are represented directly by a C_word. There's no additional memory used by them.


[C macro] C_word C_fix (int integer)


[C macro] C_word C_make_character (int char_code)


[C macro] C_word C_mk_bool(int truth_value)


[C macro] C_word C_mk_nbool(int inverted_truth_value)









Constructors for non-immediate Scheme objects

Non-immediate Scheme objects are still represented and passed around by a single C_word, but this is basically just a pointer to the start of the object (which should never be treated as such, use the accessor macros instead).


[C function] C_word C_string (C_word **ptr, int length, char *string)


[C function] C_word C_string2 (C_word **ptr, char *zero_terminated_string)


[C function] C_word C_intern2 (C_word **ptr, char *zero_terminated_string)


[C function] C_word C_intern3 (C_word **ptr, char *zero_terminated_string, C_word initial_value)


[C function] C_word C_pair (C_word **ptr, C_word car, C_word cdr)


[C function] C_word C_flonum (C_word **ptr, double number)


[C function] C_word C_int_to_num (C_word **ptr, int integer)


[C function] C_word C_mpointer (C_word **ptr, void *pointer)


[C function] C_word C_vector (C_word **ptr, int length, ...)


[C function] C_word C_list (C_word **ptr, int length, ...)


[C function] C_word C_closure (C_word **ptr, int length, C_word procedure, ...)

These functions allocate memory from ptr and initialize a fresh data object. The new data object is returned. ptr should be the address of an allocation pointer created with C_alloc.

To find out how big the memory block should be, use the C_SIZEOF_* macros described below.

Here's an example how to create a closure that accepts a vector, stores the Scheme numbers 1, 2 and 3 and a given string in it and returns that vector to its continuation:


#include <assert.h>

void fill_vector(C_word c, C_word closure, C_word vec)
  C_word kontinuation = C_block_item(closure, 1);

  C_block_item(vec, 0) = C_fix(1);
  C_block_item(vec, 1) = C_fix(2);
  C_block_item(vec, 2) = C_fix(3);
  C_block_item(vec, 3) = C_block_item(closure, 2);

  C_kontinue(kontinuation, vec);

void one_two_three(C_word c, C_word self, C_word k, C_word str)
   * Allocate room on the stack to hold the closure:  1 word for
   * the type tag, 1 word for the procedure and 2 words for the
   * values "closed over"; this procedure's continuation "k" and
   * the argument "str".  We could also use C_alloc(4).
  C_word closure[4], *cp = closure;

  /* Create the closure.  It holds 3 values, not counting the tag */
  C_word closure_object = C_closure(&cp, 3, (C_word)fill_vector, k, str);

   * After this, cp points just beyond the last word of the allocated
   * data and closure_object is an opaque representation of the newly
   * created closure as a whole, i.e. the following relations hold:
  assert(  (closure + 4) == cp  );
  assert(  C_block_header(closure_object) == (*closure)  );
  assert(  C_data_pointer(closure_object) == (closure + 1)  );
  assert(  C_block_item(closure_object, 0) == (*(closure + 1))  );

  /* Make a vector of 4 objects and use closure_object as continuation */
  C_allocate_vector(6, (C_word)NULL, closure_object, C_fix(4),
                    C_SCHEME_FALSE,  /* not a byte vector */
                    C_SCHEME_FALSE,  /* initialization value. Don't care */
                    C_SCHEME_FALSE); /* don't align at 8 bytes */
  /* .. C_allocate_vector does not return ... */

(define one-two-three (foreign-primitive ((scheme-object str)) "one_two_three(C_c, C_self, C_k, str);"))
;; Or, more direct/lowlevel:
;; (define one-two-three (##core#primitive "one_two_three"))

(print (one-two-three "hi"))

This is equivalent to the following in Scheme:

(define (one-two-three str)
  (let ((fill-vector (lambda (vec)
                       (vector-set! vec 0 1)
                       (vector-set! vec 1 2)
                       (vector-set! vec 2 3)
                       (vector-set! vec 3 str)
    (fill-vector (make-vector 4 #f))))

(print (one-two-three "hi"))

Memory allocation

These can be used to allocate memory for non-immediate objects.


[C macro] C_word* C_alloc (int words)

Allocates memory from the C stack (C_alloc) and returns a pointer to it. words should be the number of words needed for all data objects that are to be created in this function. Note that stack-allocated data objects have to be passed to Scheme callback functions, or they will not be seen by the garbage collector. This is really only usable for callback procedure invocations, make sure not to use it in normal code, because the allocated memory will be re-used after the foreign procedure returns. When invoking Scheme callback procedures a minor garbage collection is performed, so data allocated with C_alloc will already have moved to a safe place.

Note that C_alloc is really just a wrapper around alloca, and can also be simulated by declaring a stack-allocated array of C_words:


[C macro] int C_SIZEOF_LIST (int length)


[C macro] int C_SIZEOF_STRING (int length)


[C macro] int C_SIZEOF_VECTOR (int length)


[C macro] int C_SIZEOF_INTERNED_SYMBOL (int length)


[C macro] int C_SIZEOF_PAIR


[C macro] int C_SIZEOF_FLONUM


[C macro] int C_SIZEOF_POINTER





These are macros that return the size in words needed for a data object of a given type.



[C macro] int C_character_code (C_word character)


[C macro] int C_unfix (C_word fixnum)


[C macro] double C_flonum_magnitude (C_word flonum)


[C function] char* C_c_string (C_word string)


[C function] int C_num_to_int (C_word fixnum_or_flonum)


[C function] void* C_pointer_address (C_word pointer)

These macros and functions can be used to convert Scheme data objects back to C data. Note that C_c_string() returns a pointer to the character buffer of the actual Scheme object and is not zero-terminated.


[C macro] int C_header_size (C_word x)


[C macro] int C_header_bits (C_word x)

Return the number of elements and the type-bits of the non-immediate Scheme data object x.


[C macro] C_word C_block_item (C_word x, int index)

This macro can be used to access slots of the non-immediate Scheme data object x. index specifies the index of the slot to be fetched, starting at 0. Pairs have 2 slots, one for the car and one for the cdr. Vectors have one slot for each element.


[C macro] C_word C_u_i_car (C_word x)


[C macro] C_word C_u_i_cdr (C_word x)

Aliases for C_block_item(x, 0) and C_block_item(x, 1), respectively.


[C macro] C_word C_port_file (C_word x)

Alias for (FILE *)C_block_item(x, 0). To be used with port objects representing files (but will not work on sockets, for example).


[C macro] void* C_data_pointer (C_word x)

Returns a pointer to the data-section of a non-immediate Scheme object.


[C macro] C_word C_make_header (C_word bits, C_word size)

A macro to build a Scheme object header from its bits and size parts.


[C function] C_word C_mutate (C_word *slot, C_word val)

Assign the Scheme value val to the location specified by slot. If the value points to data inside the nursery (the first heap-generation), then the garbage collector will remember to handle the data appropriately. Assigning nursery-pointers directly will otherwise result in lost data. Note that no copying takes place at the moment when C_mutate is called, but later - at the next (minor) garbage collection.


[C macro] C_word C_symbol_value (C_word symbol)

Returns the global value of the variable with the name symbol. If the variable is unbound C_SCHEME_UNBOUND is returned. You can set a variable's value with C_mutate(&C_symbol_value(SYMBOL), VALUE).

GC interface


[C function] void C_gc_protect (C_word *ptrs[], int n)

Registers n variables at address ptrs to be garbage collection roots. The locations should not contain pointers to data allocated in the nursery, only immediate values or pointers to heap-data are valid. Any assignment of potential nursery data into a root-array should be done via C_mutate(). The variables have to be initialized to sensible values before the next garbage collection starts (when in doubt, set all locations in ptrs to C_SCHEME_UNDEFINED) C_gc_protect may not called before the runtime system has been initialized (either by CHICKEN_initialize, CHICKEN_run or CHICKEN_invoke.

For a slightly simpler interface to creating and using GC roots see CHICKEN_new_gc_root.


[C function] void C_gc_unprotect (int n)

Removes the last n registered variables from the set of root variables.


[C Variable] void (*C_pre_gc_hook)(int mode)

If not NULL, the function pointed to by this variable will be called before each garbage collection with a flag indicating what kind of collection was performed (either 0 for a minor collection or 2 for a resizing collection). A "resizing" collection means a secondary collection that moves all live data into a enlarged (or shrinked) heap-space. Minor collections happen very frequently, so the hook function should not consume too much time. The hook function may not invoke Scheme callbacks.

Note that resizing collections may be nested in normal major collections.


[C Variable] void (*C_post_gc_hook)(int mode, long ms)

If not NULL, the function pointed to by this variable will be called after each garbage collection with a flag indicating what kind of collection was performed (either 0 for a minor collection, 1 for a major collection or 2 for a resizing collection). Minor collections happen very frequently, so the hook function should not consume too much time. The hook function may not invoke Scheme callbacks. The ms argument records the number of milliseconds required for the garbage collection, if the collection was a major one. For minor collections the value of the ms argument is undefined.

An example for simple calls to foreign code involving callbacks

% cat foo.scm
extern int callout(int, int, int);

(define callout (foreign-safe-lambda int "callout" int int int))

(define-external (callin (scheme-object xyz)) int
  (print "This is 'callin': " xyz)

(print (callout 1 2 3))
% cat bar.c
#include <stdio.h>
#include "chicken.h"

extern int callout(int, int, int);
extern int callin(C_word x);

int callout(int x, int y, int z)
  C_word *ptr = C_alloc(C_SIZEOF_LIST(3));
  C_word lst;

  printf("This is 'callout': %d, %d, %d\n", x, y, z);
  lst = C_list(&ptr, 3, C_fix(x), C_fix(y), C_fix(z));
  return callin(lst);  /* Note: `callin' will have GC'd the data in `ptr' */
% csc foo.scm bar.c -o foo
% foo
This is 'callout': 1, 2, 3
This is 'callin': (1 2 3)


Previous: Other support procedures

Next: Extensions