2.2 Defining ffi functions

(define-ffi-function NAME C-NAME RETURN ARGS LIBRARY &optional DOCSTRING). This is a macro that defines a new Lisp function. It takes as many arguments as were in ARGS. While there is internal support for varargs functions, it is not exposed by define-ffi-function.

NAME is the symbol to define. C-NAME is a string, the name of the underlying C function.

RETURN describes the return type of the C function and ARGS describes the argument types. RETURN may either be a type-keyword or a pair of (type-keyword docstring). Similarly, ARGS may either be a list of type-keyword or a list of (type-keyword name &optional arg-docstring).

LIBRARY is the library where the C function should be found. This is just a symbol, most usually defined with define-ffi-library.

Using define-ffi-function, we can define Elisp-accessible functions as such:

(define-ffi-function test-function "test_function" :int nil test.so)
(test-function) ;=> 27
(define-ffi-function test-function-char "test_function" :char nil test.so)
(test-function-char) ;=> 27
(define-ffi-function test-c-string "test_c_string" :pointer nil test.so)
(test-c-string) ; => user-ptr
(define-ffi-function test-add "test_add" :int [:int :int] test.so)

(test-add 23 -23) ;=> 0

However, the docstring for test-add is not that great.

(describe-function 'test-add)

There is, however, a more sophisticated way to define a function that leads to better docstrings.

(define-ffi-function test-add "test_add"
  (:int "The sum of two numbers")
  ((:int a "A: The first number")
   (:int b "B: The second number"))
  test.so
  "Return the sum of A and B.")

(test-add 23 -23) ;=> 0

The benefit of this more verbose signature is better docstrings for the functions in elisp.

(describe-function 'test-add)