Next: , Previous: , Up: ffi call   [Index]

11.4.2 Calling out to foreign procedures

In order to call out to a foreign procedure, we must provide two pieces of information: the signature of the foreign procedure and the address of the procedure in memory. The signature must usually be hard–coded into the program; the address is obtained using dlsym.

Using the signature, the FFI determines how Scheme values are converted to and from native values; a signature is composed of two parts: a Scheme symbol specifying the return type, a list of Scheme symbols specifying the argument types.

Here is a simple example, without error checking, showing how to interface to the C function sinh():

(import (vicare)
  (prefix (vicare ffi) ffi::))

(define libc

(define sinh-address
  (ffi::dlsym libc "sinh"))

(define callout-maker
  (ffi::make-c-callout-maker 'double '(double)))

(define sinh
  (callout-maker sinh-address))

(sinh 1.2)      ⇒ 1.5094613554121725

using the FFI we build a callout function generator which can be used to create any number of callout functions having the same signature. Generated callout functions are garbage collected like any other Scheme value.

Function: make-c-callout-maker ret-type arg-types

Build and return a function to be used to generate callout Scheme functions wrapping foreign functions which follow the C language conventions for calling, arguments and return values.

The returned generator function accepts as single argument a pointer object representing the address of a foreign function; the value returned by the generator function is a Scheme closure wrapping the foreign function. The wrapper Scheme closure takes care of marshaling Scheme values as appropriate for the underlying platform.

ret-type must be a Scheme symbol specifying the type of the returned value; if the foreign function returns no value: ret-type must be the symbol void.

arg-types must be a list of Scheme symbols specifying the type of the arguments; if the foreign function accepts no arguments: arg-types must be nil or the list (void).

ffi call types for the specification of accepted type symbols.

Function: make-c-callout-maker/with-errno ret-type arg-types

Like make-c-callout-maker, but the generated callout closures will return two values: the return value from the foreign function call and the value of the C language variable errno right after the foreign function call.

Next: , Previous: , Up: ffi call   [Index]