Node:Defining new Scheme procedures in C, Next:, Previous:Executing Scheme code, Up:GH

19.7 Defining new Scheme procedures in C

The real interface between C and Scheme comes when you can write new Scheme procedures in C. This is done through the routine

SCM gh_new_procedure (char *proc_name, SCM (*fn)(), int n_required_args, int n_optional_args, int restp) Libguile high
gh_new_procedure defines a new Scheme procedure. Its Scheme name will be proc_name, it will be implemented by the C function (*fn)(), it will take at least n_required_args arguments, and at most n_optional_args extra arguments.

When the restp parameter is 1, the procedure takes a final argument: a list of remaining parameters.

gh_new_procedure returns an SCM value representing the procedure.

The C function fn should have the form

SCM fn (SCM req1, SCM req2, ..., SCM opt1, SCM opt2, ..., SCM rest_args) Libguile high
The arguments are all passed as SCM values, so the user will have to use the conversion functions to convert to standard C types.

Examples of C functions used as new Scheme primitives can be found in the sample programs learn0 and learn1.

Rationale: this is the correct way to define new Scheme procedures in C. The ugly mess of arguments is required because of how C handles procedures with variable numbers of arguments.

Note: what about documentation strings?

There are several important considerations to be made when writing the C routine (*fn)().

First of all the C routine has to return type SCM.

Second, all arguments passed to the C function will be of type SCM.

Third: the C routine is now subject to Scheme flow control, which means that it could be interrupted at any point, and then reentered. This means that you have to be very careful with operations such as allocating memory, modifying static data ...

Fourth: to get around the latter issue, you can use GH_DEFER_INTS and GH_ALLOW_INTS.

These macros disable and re-enable Scheme's flow control. They