# 17 SWIG and Chicken

- Preliminaries
  - Running SWIG in C mode
  - Running SWIG in C++ mode
- Code Generation
  - Naming Conventions
  - Modules
  - Constants and Variables
  - Functions
- TinyCLOS
- Compilation
- Linkage
  - Shared library
  - Static binary
- Typemaps
- Pointers
- Unsupported features and known problems

This chapter describes SWIG's support of CHICKEN. CHICKEN is a Scheme-to-C compiler supporting most of the language features as defined in the Revised^5 Report on Scheme. Its main attributes are that it

1. generates portable C code
2. includes a customizable interpreter
3. links to C libraries with a simple Foreign Function Interface
4. supports full tail-recursion and first-class continuations

When confronted with a large C library, CHICKEN users can use SWIG to generate CHICKEN wrappers for the C library. However, the real advantages of using SWIG with CHICKEN are its support for C++ -- object-oriented code is difficult to wrap by hand in CHICKEN -- and its typed pointer representation, essential for C and C++ libraries involving structures or classes.

## 17.1 Preliminaries

CHICKEN support was introduced to SWIG in version 1.3.18. SWIG relies on some recent additions to CHICKEN, which are only present in releases of CHICKEN with version number greater than or equal to `1.40`.
CHICKEN can be downloaded from http://www.call-with-current-continuation.org/ You may want to look at any of the examples in Examples/chicken/ or Examples/GIFPlot/Chicken for the basic steps to run SWIG CHICKEN. We will generically refer to the wrapper as the generated files.

### 17.1.1 Running SWIG in C mode

To run SWIG CHICKEN in C mode, use the -chicken option.

>     % swig -chicken example.i

To allow the wrapper to take advantage of future CHICKEN code generation improvements, part of the wrapper is direct CHICKEN function calls (`example_wrap.c`) and part is CHICKEN Scheme (`example.scm`). The basic Scheme code must be compiled to C using your system's CHICKEN compiler.

>     % chicken example.scm -output-file oexample.c

So for the C mode of SWIG CHICKEN, `example_wrap.c` and `oexample.c` are the files that must be compiled to object files and linked into your project.

### 17.1.2 Running SWIG in C++ mode

To run SWIG CHICKEN in C++ mode, use the -chicken -c++ option.

>     % swig -chicken -c++ example.i

This will generate `example_wrap.cxx` and `example.scm`. The basic Scheme code must be compiled to C using your system's CHICKEN compiler.

>     % chicken example.scm -output-file oexample.c

So for the C++ mode of SWIG CHICKEN, `example_wrap.cxx` and `oexample.c` are the files that must be compiled to object files and linked into your project.

## 17.2 Code Generation

### 17.2.1 Naming Conventions

Given a C variable, function or constant declaration named `Foo_Bar`, the declaration will be available in CHICKEN as an identifier ending with `Foo-Bar`. That is, an underscore is converted to a dash.
You may control what the CHICKEN identifier will be by using the `%rename` SWIG directive in the SWIG interface file.

### 17.2.2 Modules

The name of the module must be declared one of two ways:

- Placing `%module example` in the SWIG interface file.
- Using `-module example` on the SWIG command line.

The generated example.scm file then exports `(declare (unit modulename))`

CHICKEN will be able to access the module using the `(declare (uses modulename))` CHICKEN Scheme form.

### 17.2.3 Constants and Variables

Constants may be created using any of the four constructs in the interface file:

1. `#define MYCONSTANT1 ...`
2. `%constant int MYCONSTANT2 = ...`
3. `const int MYCONSTANT3 = ...`
4. `enum { MYCONSTANT4 = ... };`

In all cases, the constants may be accessed from with CHICKEN using the form `(MYCONSTANT1)`; that is, the constants may be accessed using the read-only parameter form.

Variables are accessed using the full parameter form. For example, to set the C variable "int my_variable;", use the Scheme form `(my-variable 2345)`. To get the C variable, use `(my-variable)`.

### 17.2.4 Functions

C functions declared in the SWIG interface file will have corresponding CHICKEN Scheme procedures. For example, the C function "int sqrt(double x);" will be available using the Scheme form `(sqrt 2345.0)`. A `void` return value will give C_SCHEME_UNDEFINED as a result.

A function may return more than one value by using the `OUTPUT` specifier (see Lib/chicken/typemaps.i). They will be returned as a Scheme list if there is more than one result (that is, a non-void return value and at least one argout parameter, or a void return value and at least two argout parameters).

## 17.3 TinyCLOS

The author of TinyCLOS, Gregor Kiczales, describes TinyCLOS as:

> Tiny CLOS is a Scheme implementation of a `kernelized' CLOS, with a metaobject protocol. The implementation is even simpler than the simple CLOS found in `The Art of the Metaobject Protocol,' weighing in at around 850 lines of code, including (some) comments and documentation.

Almost all good Scheme books describe how to use metaobjects and generic procedures to implement an object-oriented Scheme system. Please consult a Scheme book if you are unfamiliar with the concept.

CHICKEN has a modified version of TinyCLOS, which SWIG CHICKEN uses if the -proxy argument is given. If -proxy is passed, then the generated example.scm file will contain TinyCLOS class definitions. A class named Foo is declared as <Foo>, and each member variable is allocated a slot. Member functions are exported as generic functions.

Primitive symbols and functions (the interface that would be presented if -proxy was not passed) are hidden and no longer accessable. If the -unhideprimitive command line argument is passed to SWIG, then the primitive symbols will be available, but each will be prefixed by the string "primitive:"

The exported symbol names can be controlled with the -closprefix and -useclassprefix arguments. If -useclassprefix is passed to SWIG, every member function will be generated with the class name as a prefix. If the -closprefix mymod: argument is passed to SWIG, then the exported functions will be prefixed by the string "mymod:". If -useclassprefix is passed, -closprefix is ignored.

## 17.4 Compilation

Please refer to CHICKEN - A practical and portable Scheme system - User's manual for detailed help on how to compile C code for use in a CHICKEN program. Briefly, to compile C code, be sure to add ``chicken-config -cflags`` or ``chicken-config -shared -cflags`` to your compiler options. Use the `-shared` option if you want to create a dynamically loadable module. You might also want to use the much simpler `csc` or `csc.bat`.

## 17.5 Linkage

Please refer to CHICKEN - A practical and portable Scheme system - User's manual for detailed help on how to link object files to create a CHICKEN Scheme program. Briefly, to link object files, be sure to add ``chicken-config -extra-libs -libs`` or ``chicken-config -shared -extra-libs -libs``to your linker options. Use the `-shared` option if you want to create a dynamically loadable module.

### 17.5.1 Shared library

The easiest way to use SWIG and CHICKEN is to use the csc compiler wrapper provided by CHICKEN. Assume you have a SWIG interface file in example.i and the C functions being wrapped are in example_impl.c.

>        $ swig -chicken example.i
>        $ csc -svk example.scm example_impl.c example_wrap.c
>        $ csi example.so test_script.scm

You must be careful not to name the example_impl.c file example.c because when compiling example.scm, csc compiles that into example.c!

The test_script.scm should have `(load-library 'example "example.so")` and `(declare (uses example))`. As well, the path to example.so should be accessable to the loader. You might need to set LD_LIBRARY_PATH.

### 17.5.2 Static binary

Again, we can easily use csc to build a binary.

>        $ swig -chicken example.i
>        $ csc -vk example.scm example_impl.c example_wrap.c test_script.scm -o example
>        $ ./example

## 17.6 Typemaps

The Chicken module handles all types via typemaps. This information is read from `Lib/chicken/typemaps.i` and `Lib/chicken/chicken.swg`.

## 17.7 Pointers

For pointer types, SWIG uses CHICKEN tagged pointers. A tagged pointer is an ordinary CHICKEN pointer with an extra slot for a void *. With SWIG CHICKEN, this void * is a pointer to a type-info structure. So each pointer used as input or output from the SWIG-generated CHICKEN wrappers will have type information attached to it. This will let the wrappers correctly determine which method should be called according to the object type hierarchy exposed in the SWIG interface files.

To construct a Scheme object from a C pointer, the wrapper code calls the function `SWIG_NewPointerObj(void *ptr, swig_type_info *type, int owner)`, The function that calls `SWIG_NewPointerObj` must have a variable declared `C_word *known_space = C_alloc(C_SIZEOF_SWIG_POINTER);` It is ok to call `SWIG_NewPointerObj` more than once, just make sure known_space has enough space for all the created pointers.

To get the pointer represented by a CHICKEN tagged pointer, the wrapper code calls the function `SWIG_ConvertPtr(C_word s, void **result, swig_type_info *type, int flags)`, passing a pointer to a struct representing the expected pointer type.

## 17.8 Unsupported features and known problems

- No exception handling.
- No director support.
- No support for c++ standard types like std::vector.
- No support for automatic garbage collection of wrapped classes and structures. (Planned on adding in SWIG version 1.3.24)
- Importing multiple SWIG modules not working with TinyCLOS. (Planned on fixing for 1.3.24)
- Problems with complicated function overloading. (Planned on fixing for 1.3.24)