Next: , Previous: , Up: Foreign Types   [Contents][Index]


6.3 Defining Foreign Types

You can define simple C-like typedefs through the defctype macro. Defining a typedef is as simple as giving defctype a new name and the name of the type to be wrapped.

  ;;; Define MY-INT as an alias for the built-in type :INT.
  (defctype my-int :int)

With this type definition, one can, for instance, declare arguments to foreign functions as having the type my-int, and they will be passed as integers.

More complex types

CFFI offers another way to define types through define-foreign-type, a thin wrapper macro around defclass. As an example, let’s go through the steps needed to define a (my-string &key encoding) type. First, we need to define our type class:

  (define-foreign-type my-string-type ()
    ((encoding :reader string-type-encoding :initarg :encoding))
    (:actual-type :pointer))

The :actual-type class option tells CFFI that this type will ultimately be passed to and received from foreign code as a :pointer. Now you need to tell CFFI how to parse a type specification such as (my-string :encoding :utf8) into an instance of my-string-type. We do that with define-parse-method:

  (define-parse-method my-string (&key (encoding :utf-8))
    (make-instance 'my-string-type :encoding encoding))

The next section describes how make this type actually translate between C and Lisp strings.