6.19.5 Foreign Functions

The most natural thing to do with a dynamic library is to grovel around in it for a function pointer: a foreign function. Load the (system foreign) module to use these Scheme interfaces.

(use-modules (system foreign))
Scheme Procedure: pointer->procedure return_type func_ptr arg_types [#:return-errno?=#f]
C Function: scm_pointer_to_procedure (return_type, func_ptr, arg_types)
C Function: scm_pointer_to_procedure_with_errno (return_type, func_ptr, arg_types)

Make a foreign function.

Given the foreign void pointer func_ptr, its argument and return types arg_types and return_type, return a procedure that will pass arguments to the foreign function and return appropriate values.

arg_types should be a list of foreign types. return_type should be a foreign type. See Foreign Types, for more information on foreign types.

If return-errno? is true, or when calling scm_pointer_to_procedure_with_errno, the returned procedure will return two values, with errno as the second value.

Finally, in (system foreign-library) there is a convenient wrapper function, joining together foreign-library-pointer and procedure->pointer:

Scheme Procedure: foreign-library-function lib name [#:return-type=void] [#:arg-types=’()] [#:return-errno?=#f]

Load the address of name from lib, and treat it as a function taking arguments arg-types and returning return-type, optionally also with errno.

An invocation of foreign-library-function is entirely equivalent to:

(pointer->procedure return-type
                    (foreign-library-pointer lib name)
                    arg-types
                    #:return-errno? return-errno?).

Pulling all this together, here is a better definition of (math bessel):

(define-module (math bessel)
  #:use-module (system foreign)
  #:use-module (system foreign-library)
  #:export (j0))

(define j0
  (foreign-library-function "libm" "j0"
                            #:return-type double
                            #:arg-types (list double)))

That’s it! No C at all.

Before going on to more detailed examples, the next two sections discuss how to deal with data that is more complex than, say, int8. See More Foreign Functions, to continue with foreign function examples.