Next: , Previous: Libraries, Up: Top


7 C interface

(This chapter was derived from work copyrighted (C) 1993-2005 by Richard Kelsey, Jonathan Rees, and Mike Sperber.)

This chapter describes an interface for calling C functions from Scheme, calling Scheme procedures from C, and working with the Scheme heap in C. Scheme48 manages stub functions in C that negotiate between the calling conventions of Scheme & C and the memory allocation policies of both worlds. No stub generator is available yet, but writing stubs is a straightforward task.

7.1 Overview of the C interface

The following facilities are available for interfacing between Scheme48 & C:

7.1.1 Scheme structures

On the Scheme side of the C interface, there are three pertinent structures: shared-bindings, which provides the Scheme side of the facility for sharing data between Scheme and C; external-calls, which exports several ways to call C functions from Scheme, along with some useful facilities, such as object finalizers, which are also available from elsewhere; and load-dynamic-externals, which provides a dynamic external object loading facility. Also, the old dynamic loading facility is still available from the dynamic-externals structure, but its use is deprecated, and it will most likely vanish in a later release.

7.1.2 C naming conventions

Scheme48's C bindings all have strict naming conventions. Variables & procedures have s48_ prefixed to them; macros, S48_. Whenever a C name is derived from a Scheme identifier, hyphens are replaced with underscores. Also, procedures or variables are converted to lowercase, while macros are converted to uppercase. The ? suffix, generally appended to predicates, is converted to _p (or _P in macro names). Trailing ! is dropped. For example, the C macro that corresponds with Scheme's pair? predicate is named S48_PAIR_P, and the C macro to assign the car of a pair is named S48_SET_CAR. Procedures and macros that do not verify the types of their arguments have `unsafe' in their names.

All of the C functions and macros described have prototypes or definitions in the file c/scheme48.h of Scheme48's standard distribution. The C type for Scheme values is defined there to be s48_value.

7.1.3 Garbage collection

Scheme48 uses a copying garbage collector. The collector must be able to locate all references to objects allocated in the Scheme48 heap in order to ensure that storage is not reclaimed prematurely and to update references to objects moved by the collector. The garbage collector may run whenever an object is allocated in the heap. C variables whose values are Scheme48 objects and which are live across heap allocation calls need to be registered with the garbage collector. For more information, see Interacting with the Scheme heap in C.