Next: , Up: Alien Function Calls   [Contents][Index]

8.7.1 The alien-funcall Primitive

Function: alien:alien-funcall alien-function &rest arguments

This function is the foreign function call primitive: alien-function is called with the supplied arguments and its value is returned. The alien-function is an arbitrary run-time expression; to call a constant function, use extern-alien or def-alien-routine.

The type of alien-function must be (alien (function ...)) or (alien (* (function ...))), See alien-function-types. The function type is used to determine how to call the function (as though it was declared with a prototype.) The type need not be known at compile time, but only known-type calls are efficiently compiled. Limitations:

Here is an example which allocates a (struct foo), calls a foreign function to initialize it, then returns a Lisp vector of all the (* (struct foo)) objects filled in by the foreign call:

;; Allocate a foo on the stack.
(with-alien ((f (struct foo)))
  ;; Call some C function to fill in foo fields.
  (alien-funcall (extern-alien "mangle_foo" (function void (* foo)))
                 (addr f))
  ;; Find how many foos to use by getting the A field.
  (let* ((num (slot f 'a))
         (result (make-array num)))
    ;; Get a pointer to the array so that we don't have to keep
    ;; extracting it:
    (with-alien ((a (* (array (* (struct foo)) 100)) (addr (slot f 'b))))
      ;; Loop over the first N elements and stash them in the
      ;; result vector.
      (dotimes (i num)
        (setf (svref result i) (deref (deref a) i)))