Introduction

The foreign.ss library enables the direct use of C-based APIs within Scheme programs (i.e., without writing any new C code). From the Scheme perspective, functions and data with a C-based API are foreign, hence the term foreign interface. Furthermore, since most APIs consist mostly of functions, the foreign interface is sometimes called a foreign function interface, abbreviated FFI.

Although using the FFI requires writing no new C code, it provides very little insulation against the issues that C programmer faces related to safety and memory management. An FFI programmer must be particularly aware of memory management issues for data that spans the Scheme-C divide. Thus, this manual relies in many ways on the information in Inside PLT MzScheme, which defines how MzScheme interacts with C APIs in general.

Since using the FFI entails many safety concerns that Scheme programmers can normally ignore, merely importing foreign.ss with (require (lib "foreign.ss")) does not import all of the FFI functionality. Only safe functionality is immediately imported. For example, ptr-equal? can never cause memory corruption or an invalid memory access, so it is immediately available on import.

Use (unsafe!) at the top-level of a module that imports foreign.ss to make unsafe features accessible.1 Using this macro should be considered as a declaration that your code is itself unsafe, therefore can lead to serious problems in case of bugs: it is your responsibility to provide a safe interface.

In rare cases, you might want to provide an unsafe interface hat builds on the unsafe features of the FFI. In such cases, use the provide* macro with unsafe bindings, and use define-unsafer to provide an unsafe!-like macro that will make these bindings available to importers of your library. Providing users with unsafe operations without using this facility should be considered a bug in your code.

For examples of common FFI usage patterns, see the defined interfaces in the ffi collection.


1 For additional safety, the unsafe! is itself protected (see section 9.4 in PLT MzScheme: Language Manual).