To enable an external C function to call back to Scheme, the form foreign-callback-lambda (or foreign-callback-lambda*) has to be used. This generates special code to save and restore important state information during execution of C code. There are two ways of calling Scheme procedures from C: the first is to invoke the runtime function C_callback with the closure to be called and the number of arguments. The second is to define an externally visible wrapper function around a Scheme procedure with the define-external or foreign-callback-wrapper forms.
Note: the names of all functions, variables and macros exported by the Chicken runtime system start with ``C_''. It is advisable to use a different naming scheme for your own code to avoid name clashes. Callbacks (either defined by define-external or foreign-callback-wrapper do not capture the lexical environment.
(define-external (foo (c-string x)) int (string-length x))
is equivalent to
(define foo (foreign-callback-wrapper int "foo" (c-string) (lambda (x) (string-length x))))
The second form of define-external can be used to define variables that are accessible from foreign code. It declares a global variable named by the symbol NAME that has the type TYPE. INIT can be an arbitrary expression that is used to initialize the variable. NAME is accessible from Scheme just like any other foreign variable defined by define-foreign-variable.
(define-external foo int 42) ((foreign-lambda* int () "return(foo);")) ==> 42
Note: don't be tempted to assign strings or bytevectors to external variables. Garbage collection moves those objects around, so it is very bad idea to assign pointers to heap-data. If you have to do so, then copy the data object into statically allocated memory (for example by using object-evict).