Package: cffi

Macro defcvar

Lambda List

defcvar (name-and-options type &optional documentation)


name-and-options -- ::= name | (name &key read-only (library :default))
name -- ::= lisp-name [foreign-name] | foreign-name [lisp-name]
foreign-name -- A string denoting a foreign function.
type -- A foreign type.
read-only -- A boolean.
documentation -- A Lisp string; not evaluated.

Return Value

A symbol naming the Lisp function to be created.


The defcvar macro defines a symbol macro lisp-name that looks up foreign-name and dereferences it acording to type. It can also be setfed, unless read-only is true, in which case an error will be signaled.

When one of lisp-name or foreign-name is omitted, the other is automatically derived using the following rules:
  • Foreign names are converted to Lisp names by uppercasing, replacing underscores with hyphens, and wrapping around asterisks.
  • Lisp names are converted to foreign names by lowercasing, replacing hyphens with underscores, and removing asterisks, if any.


  CFFI> (defcvar "errno" :int)
  => *ERRNO*
  CFFI> (foreign-funcall "strerror" :int *errno* :string)
  => "Inappropriate ioctl for device"
  CFFI> (setf *errno* 1)
  => 1
  CFFI> (foreign-funcall "strerror" :int *errno* :string)
  => "Operation not permitted"  
Trying to modify a read-only foreign variable:
  CFFI> (defcvar ("errno" +error-number+ :read-only t) :int)
  CFFI> (setf +error-number+ 12)
  ;; error--> Trying to modify read-only foreign var: +ERROR-NUMBER+.  
Note that accessing errno this way won't work with every implementation of the C standard library.

See also