Tuesday, December 27, 2005

Scheme Foreign Functions with Chicken

I like programming in 'C'. It is great for the low-level hardware peeks and pokes but rather tedious for the high-level application. I would like my programming language to provide a certain abstraction boundary where the platform fiddly-bits are hidden from the application but still accessible when the time is appropriate. Scheme does that very well with it's Foreign Function Interface.

Chicken offers several interesting FFI variants. I present a simple example in this post. Why is it called Chicken? Well, it emits 'C' code and calls GCC or other compiler to compile the Scheme language or an extension. But you need Scheme to generate the code in the first place? It's a chicken-and-egg kind of thing. See call-with-continuation.org for a better explanation.

;;; -*- scheme-mode -*-
;;; Inline 'C' code with Chicken Scheme
(define inline-cube
(foreign-lambda* int ((int num))
"int result = (num * num * num);"
"printf(\"inline cube of %d is \",num);"
( print (inline-cube 13))
( display "goodbye\n" )
------------ console printout ------------
$ csc test2.scm
$ test2
inline cube of 13 is 2197

Well, this example is somewhat un-Scheme-ly but I included Lambda to make it more so.