home *** CD-ROM | disk | FTP | other *** search
/ Amiga ISO Collection / AmigaUtilCD2.iso / Programming / Misc / CLISP-1.LHA / CLISP960530-sr.lha / doc / foreign.txt < prev    next >
Encoding:
Text File  |  1996-04-15  |  22.3 KB  |  620 lines

  1.                  The Foreign Function Call Facility
  2.                  ==================================
  3.  
  4. A foreign function description is written as a Lisp file,
  5. and when compiled it produces a .c file which is then compiled
  6. by the C compiler and may be linked together with lisp.a.
  7.  
  8. All symbols relating to the foreign function interface are exported from
  9. the package FFI. To use them, (USE-PACKAGE "FFI").
  10.  
  11. Special FFI forms may appear anywhere in the Lisp file.
  12.  
  13.                                 Overview
  14.                                 --------
  15.  
  16. These are the special FFI forms. We have taken a pragmatic approach:
  17. the only foreign languages we support for now are C and ANSI C.
  18.  
  19. (DEF-C-TYPE name <c-type>)
  20.  
  21. (DEF-C-VAR name {option}*)
  22.   option ::=
  23.       (:name <c-name>)
  24.     | (:type <c-type>)
  25.     | (:read-only <boolean>)
  26.     | (:alloc <allocation>)
  27.  
  28. (DEF-CALL-OUT name {option}*)
  29.   option ::=
  30.       (:name <c-name>)
  31.     | (:arguments {(arg-name <c-type> [<param-mode> [<allocation>]])}*)
  32.     | (:return-type <c-type> [<allocation>])
  33.     | (:language <language>)
  34.  
  35. (DEF-CALL-IN name {option}*)
  36.   option ::=
  37.       (:name <c-name>)
  38.     | (:arguments {(arg-name <c-type> [<param-mode> [<allocation>]])}*)
  39.     | (:return-type <c-type> [<allocation>])
  40.     | (:language <language>)
  41.  
  42. (DEF-C-CALL-OUT name {option}*)
  43.   option ::=
  44.       (:name <c-name>)
  45.     | (:arguments {(arg-name <c-type> [<param-mode> [<allocation>]])}*)
  46.     | (:return-type <c-type> [<allocation>])
  47.  
  48. (DEF-C-CALL-IN name {option}*)
  49.   option ::=
  50.       (:name <c-name>)
  51.     | (:arguments {(arg-name <c-type> [<param-mode> [<allocation>]])}*)
  52.     | (:return-type <c-type> [<allocation>])
  53.  
  54. (DEF-C-STRUCT name (<ident> <c-type>)*)
  55.  
  56. (DEF-C-ENUM <name> {<ident> | (<ident> [<value>])}*)
  57.  
  58. (ELEMENT c-place {index}*)
  59. (DEREF c-place)
  60. (SLOT c-place slot-name)
  61. (CAST c-place <c-type>)
  62.  
  63. (TYPEOF c-place)
  64. (SIZEOF c-place), (SIZEOF <c-type>)
  65. (BITSIZEOF c-place), (BITSIZEOF <c-type>)
  66.  
  67. (VALIDP foreign-entity)
  68.  
  69. name is any Lisp symbol.
  70.  
  71. <c-name> is a string.
  72.  
  73.                        (Foreign) C types
  74.                        -----------------
  75.  
  76. Foreign C types are used in the FFI. They are *not* regular Common Lisp
  77. types or CLOS classes.
  78.  
  79. A <c-type> is either a predefined C type or the name of a type defined by
  80. DEF-C-TYPE.
  81.  
  82. The simple C types are these:
  83.  
  84.  Lisp name     Lisp equiv           C equiv        ILU equiv
  85.   nil           NIL                  void                             (o)
  86.   boolean       (MEMBER NIL T)       int            BOOLEAN
  87.   character     STRING-CHAR          char           SHORT CHARACTER
  88.   char          INTEGER              signed char
  89.   uchar         INTEGER              unsigned char
  90.   short         INTEGER              short
  91.   ushort        INTEGER              unsigned short
  92.   int           INTEGER              int
  93.   uint          INTEGER              unsigned int
  94.   long          INTEGER              long
  95.   ulong         INTEGER              unsigned long
  96.   uint8         (UNSIGNED-BYTE 8)    uint8          BYTE
  97.   sint8         (SIGNED-BYTE 8)      sint8
  98.   uint16        (UNSIGNED-BYTE 16)   uint16         SHORT CARDINAL
  99.   sint16        (SIGNED-BYTE 16)     sint16         SHORT INTEGER
  100.   uint32        (UNSIGNED-BYTE 32)   uint32         CARDINAL
  101.   sint32        (SIGNED-BYTE 32)     sint32         INTEGER
  102.   uint64        (UNSIGNED-BYTE 64)   uint64         LONG CARDINAL     (*)
  103.   sint64        (SIGNED-BYTE 64)     sint64         LONG INTEGER      (*)
  104.   single-float  SINGLE-FLOAT         float
  105.   double-float  DOUBLE-FLOAT         double
  106. (o) as a result type only.
  107. (*) does not work on all platforms.
  108.  
  109. The predefined C types are:
  110.  
  111.   c-type ::=
  112.       <simple-c-type>
  113.     | C-POINTER
  114.     | C-STRING
  115.     | (C-STRUCT <class> (<ident> <c-type>)*)
  116.     | (C-UNION (<ident> <c-type>)*)
  117.     | (C-ARRAY <c-type> dimensions)
  118.         dimensions ::= number | ({number}*)
  119.     | (C-ARRAY-MAX <c-type> maxdimension)
  120.         maxdimension ::= number
  121.     | (C-FUNCTION {option}*)
  122.         option ::=
  123.             (:arguments {(arg-name <c-type> [<param-mode> [<allocation>]])}*)
  124.           | (:return-type <c-type> [<allocation>])
  125.           | (:language <language>)
  126.     | (C-PTR <c-type>)
  127.     | (C-PTR-NULL <c-type>)
  128.     | (C-ARRAY-PTR <c-type>)
  129.  
  130. (DEF-C-TYPE name <c-type>)
  131. makes name a shortcut for <c-type>. Note that <c-type> may already refer
  132. to name. Forward declarations of types are not possible, however.
  133.  
  134. The type C-POINTER corresponds to what C calls "void*", an opaque pointer.
  135.  
  136. The type C-STRING corresponds to what C calls "char*", a zero-terminated
  137. string. Its Lisp equivalent is a string, without the trailing zero character.
  138.  
  139. The type (C-STRUCT class (ident1 type1) ... (ident2 type2)) is equivalent to
  140. what C calls "struct { type1 ident1; ...; type2 ident2; }". Its Lisp
  141. equivalent is: if class is VECTOR, a simple-vector; if class is LIST, a list;
  142. if class is a symbol naming a structure or CLOS class: an instance of this
  143. class, with slots of names ident1,...,ident2.
  144.  
  145. The type (C-UNION (ident1 type1) ... (ident2 type2)) is equivalent to what C
  146. calls "union { type1 ident1; ...; type2 ident2; }". Conversion to and from
  147. Lisp assumes that a value is to be viewed as being of type1.
  148.  
  149. The type (C-ARRAY type dim1 ... dim2) is equivalent to what C calls
  150. "type [dim1]...[dim2]". Note that when an array is passed as an argument to
  151. a function in C, it is actually passed as a pointer; you therefore have to
  152. write (C-PTR (C-ARRAY ...)) for this argument's type.
  153.  
  154. The type (C-ARRAY-MAX type maxdim) is equivalent to what C calls
  155. "type [maxdim]", an array containing up to maxdim elements. The array is
  156. zero-terminated if it contains less than maxdim elements. Conversion from Lisp
  157. of an array with more than maxdim elements silently ignores the superfluous
  158. elements.
  159.  
  160. The type (C-PTR type) is equivalent to what C calls "type *": a pointer to
  161. a single item of the given type.
  162.  
  163. The type (C-PTR-NULL type) is also equivalent to what C calls 
  164. "type *": a pointer to a single item of the given type.  C-PTR-NULL
  165. implicits converts NIL into NULL.
  166.  
  167. The type (C-ARRAY-PTR type) is equivalent to what C calls "type (*)[]":
  168. a pointer to a zero-terminated array of items of the given type.
  169.  
  170. The type (C-FUNCTION (:return-type rtype) (:arguments (arg1 type1 ...) ...))
  171. designates a C function that can be called according to the given prototype
  172. (rtype (*) (type1, ...)).
  173. The <language> is either :C (denotes K&R C) or :STDC (denotes ANSI C). It
  174. specifies whether the C function has been compiled by a K&R C compiler or by
  175. an ANSI C compiler.
  176. Conversion between C functions and Lisp functions is transparent.
  177.  
  178. (DEF-C-STRUCT <name> (<ident> <c-type>)*) defines <name> to be both a
  179. DEFSTRUCT structure type and a foreign C type with the given slots.
  180.  
  181. (DEF-C-ENUM <name> {<ident> | (<ident> [<value>])}*) defines <ident>s as
  182. constants, similarly to the C declaration  enum { <ident> [= <value>], ... };
  183.  
  184. The form (SIZEOF <c-type>) returns the size and alignment of a C type,
  185. measured in bytes.
  186.  
  187. The form (BITSIZEOF <c-type>) returns the size and alignment of a C type,
  188. measured in bits.
  189.  
  190. The predicate (VALIDP foreign-entity) returns NIL if the foreign-entity
  191. (e.g. the Lisp equivalent of a C-POINTER) refers to a pointer which is
  192. invalid because it comes from a previous Lisp session. It returns T if
  193. foreign-entity can be used within the current Lisp process.
  194.  
  195.                        Foreign variables
  196.                        -----------------
  197.  
  198. Foreign variables are variables whose storage is allocated in the foreign
  199. language module. They can nevertheless be evaluated and modified through SETQ,
  200. just as normal variables can, except that the range of allowed values is
  201. limited according to the variable's foreign type. Note that for a foreign
  202. variable X the form (EQL X X) is not necessarily true, since every time X is
  203. evaluated its foreign value is converted to a freshly created Lisp value.
  204.  
  205. (DEF-C-VAR name {option}*)
  206.   option ::=
  207.       (:name <c-name>)
  208.     | (:type <c-type>)
  209.     | (:read-only <boolean>)
  210.     | (:alloc <allocation>)
  211.  
  212. defines a foreign variable. `name' is the Lisp name, a regular Lisp symbol.
  213.  
  214. The :name option specifies the name, as seen from C, as a string. If not
  215. specified, it is derived from the print name of the Lisp name.
  216.  
  217. The :type option specifies the variable's foreign type.
  218.  
  219. If the :read-only option is specified and non-NIL, it will be impossible
  220. to change the variable's value from within Lisp (using SETQ or similar).
  221.  
  222. The :alloc option can be either :NONE or :MALLOC-FREE and defaults to
  223. :NONE.  If it is :MALLOC-FREE, any values of type C-STRING, 
  224. (C-PTR ...), (C-PTR-NULL ...), (C-ARRAY-PTR ...) within the foreign
  225. value are assumed to be pointers to malloc()-allocated storage, and
  226. when SETQ replaces an old value by a new one, the old storage is freed
  227. using free() and the new storage allocated using malloc(). If it is
  228. :NONE, SETQ assumes that the pointers point to good storage (not
  229. NULL!) and overwrites the old values by the new ones. This is
  230. dangerous (just think of overwriting a string with a longer one or
  231. storing some data in a NULL pointer...) and deprecated.
  232.  
  233.                    Operations on foreign places
  234.                    ----------------------------
  235.  
  236. A foreign variable `name' defined by DEF-C-VAR defines a "place", i.e.
  237. a form which can also be used as argument to SETF. (An "lvalue" in C
  238. terminology.) The following operations are available on foreign places:
  239.  
  240. (ELEMENT place index1 ... indexn)
  241. Array element: If place is of foreign type (C-ARRAY <c-type> dim1 ... dimn)
  242. and 0 <= index1 < dim1, ..., 0 <= indexn < dimn, this will be the place
  243. corresponding to (aref place index1 ... indexn) or place[index1]...[indexn].
  244. It is a place of type <c-type>.
  245. If place is of foreign type (C-ARRAY-MAX <c-type> dim) and 0 <= index < dim,
  246. this will be the place corresponding to (aref place index) or place[index].
  247. It is a place of type <c-type>.
  248.  
  249. (DEREF place) Dereference pointer: If place is of foreign type 
  250. (C-PTR <c-type>) or (C-PTR-NULL <c-type>) this will be the place the
  251. pointer points to. It is a place of type <c-type>.
  252.  
  253. (SLOT place slot-name)
  254. Struct or union component: If place is of foreign type
  255. (C-STRUCT <class> ... (slot-name <c-type>) ...) or of type
  256. (C-UNION ... (slot-name <c-type>) ...), this will be of type <c-type>.
  257.  
  258. (CAST place <c-type>)
  259. Type change: A place denoting the same memory locations as the original place,
  260. but of type <c-type>.
  261.  
  262. (TYPEOF place)
  263. returns the <c-type> corresponding to the place.
  264.  
  265. (SIZEOF place) returns the size and alignment of the C type of place,
  266. measured in bytes.
  267.  
  268. (BITSIZEOF place) returns the size and alignment of the C type of place,
  269. measured in bits.
  270.  
  271.                        Foreign functions
  272.                        -----------------
  273.  
  274. Foreign functions are functions which are defined in the foreign language.
  275. There are named foreign functions (imported via DEF-CALL-OUT or created via
  276. DEF-CALL-IN) and anonymous foreign functions; they arise through conversion
  277. of function pointers.
  278.  
  279. A "call-out" function is a foreign function called from Lisp: control flow
  280. temporarily leaves Lisp.
  281. A "call-in" function is a Lisp function called from the foreign language:
  282. control flow temporary enters Lisp.
  283.  
  284. (DEF-CALL-OUT name {option}*)
  285.   option ::=
  286.       (:name <c-name>)
  287.     | (:arguments {(arg-name <c-type> [<param-mode> [<allocation>]])}*)
  288.     | (:return-type <c-type> [<allocation>])
  289.     | (:language <language>)
  290.  
  291. defines a named call-out function. Any Lisp function call to #'name is
  292. redirected to call the C function <c-name>.
  293.  
  294. DEF-C-CALL-OUT is equivalent to DEF-CALL-OUT with :LANGUAGE :C.
  295.  
  296. (DEF-CALL-IN name {option}*)
  297.   option ::=
  298.       (:name <c-name>)
  299.     | (:arguments {(arg-name <c-type> [<param-mode> [<allocation>]])}*)
  300.     | (:return-type <c-type> [<allocation>])
  301.     | (:language <language>)
  302.  
  303. defines a named call-in function. Any C function call to the C function
  304. <c-name> is redirected to call the Lisp function #'name.
  305.  
  306. DEF-C-CALL-IN is equivalent to DEF-CALL-IN with :LANGUAGE :C.
  307.  
  308.               Argument and result passing conventions
  309.               ---------------------------------------
  310.  
  311. When passed to and from functions, allocation of arguments and results is
  312. handled as follows:
  313.  
  314. Values of <simple-c-type>, C-POINTER are passed on the stack, with dynamic
  315. extent. The <allocation> is effectively ignored.
  316.  
  317. Values of type C-STRING, (C-PTR ...), (C-PTR-NULL ...), (C-ARRAY-PTR ...) 
  318. need storage. The <allocation> specifies the allocation policy:
  319.   <allocation> is :NONE          means that no storage is allocated.
  320.   <allocation> is :ALLOCA        means allocation of storage on the stack,
  321.                                        which has dynamic extent.
  322.   <allocation> is :MALLOC-FREE   means that storage will be allocated
  323.                                        via malloc() and freed via free().
  324. If no <allocation> is specified, the default <allocation> is :NONE for most
  325. types, but :ALLOCA for C-STRING, (C-PTR ...), (C-PTR-NULL ...), and
  326.  (C-ARRAY-PTR ...) and for :OUT arguments. [Subject to change!]
  327. The :MALLOC-FREE policy provides the ability to pass arbitrarily nested
  328. structs containing pointers pointing to structs ... within a single conversion.
  329.  
  330. For call-out functions:
  331.   For arguments passed from Lisp to C:
  332.     If <allocation> is :MALLOC-FREE,
  333.        Lisp allocates the storage using malloc() and never deallocates it.
  334.        The C function is supposed to call free() when done with it.
  335.     If <allocation> is :ALLOCA,
  336.        Lisp allocates the storage on the stack, with dynamic extent. It is
  337.        freed when the C function returns.
  338.     If <allocation> is :NONE,
  339.        Lisp assumes that the pointer already points to a valid area of the
  340.        proper size and puts the result value there. This is dangerous! and
  341.        deprecated.
  342.   For results passed from C to Lisp:
  343.     If <allocation> is :MALLOC-FREE,
  344.        Lisp calls free() on it when done.
  345.     If <allocation> is :NONE,
  346.        Lisp does nothing.
  347. For call-in functions:
  348.   For arguments passed from C to Lisp:
  349.     If <allocation> is :MALLOC-FREE,
  350.        Lisp calls free() on it when done.
  351.     If <allocation> is :ALLOCA or :NONE,
  352.        Lisp does nothing.
  353.   For results passed from Lisp to C:
  354.     If <allocation> is :MALLOC-FREE,
  355.        Lisp allocates the storage using malloc() and never deallocates it.
  356.        The C function is supposed to call free() when done with it.
  357.     If <allocation> is :NONE,
  358.        Lisp assumes that the pointer already points to a valid area of the
  359.        proper size and puts the result value there. This is dangerous! and
  360.        deprecated.
  361.  
  362. A function parameter's <param-mode> may be
  363. either :IN (means: read-only):
  364.        The caller passes information to the callee.
  365. or     :OUT (means: write-only):
  366.        The callee passes information back to the caller on return.
  367.        When viewed as a Lisp function, there is no Lisp argument corresponding
  368.        to this, instead it means an additional return value.
  369. or     :IN-OUT (means: read-write):
  370.        Information is passed from the caller to the callee and then back to
  371.        the caller. When viewed as a Lisp function, the ":OUT" value is
  372.        returned as an additional multiple value.
  373. The default is :IN.
  374.  
  375. [Currently, only :IN is fully implemented. :OUT works only with
  376. <allocation> = :ALLOCA.]
  377.  
  378. On AmigaOS, <allocation> may not be :MALLOC-FREE because there is no commonly
  379. used malloc()/free() library function.
  380.  
  381. On AmigaOS, the <allocation> may be followed by a register specification,
  382. any of the symbols :D0, :D1, :D2, :D3, :D4, :D5, :D6, :D7, :A0, :A1, :A2,
  383. :A3, :A4, :A5, :A6, each representing one 680x0 register. This works only
  384. for integral types: integers, pointers, C-STRING, C-FUNCTION.
  385.  
  386. Passing C-STRUCT, C-UNION, C-ARRAY, C-ARRAY-MAX values as arguments (not via
  387. pointers) is only possible to the extent the C compiler supports it. Most C
  388. compilers do it right, but some C compilers (such as gcc on hppa) have
  389. problems with this.
  390.  
  391.                            Examples
  392.                            --------
  393.  
  394. Ex. 1: The C declaration
  395.  
  396.        struct foo {
  397.            int a;
  398.            struct foo * b[100];
  399.        };
  400.  
  401. corresponds to
  402.  
  403.        (def-c-struct foo
  404.          (a int)
  405.          (b (c-array (c-ptr foo) 100))
  406.        )
  407.  
  408. The element access
  409.  
  410.        struct foo f;
  411.        f.b[7].a
  412.  
  413. corresponds to
  414.  
  415.        (declare (type foo f))
  416.        (foo-a (aref (foo-b f) 7)) or (slot-value (aref (slot-value f 'b) 7) 'a)
  417.  
  418. Ex. 2: Here is an example of an external C variable and some accesses:
  419.  
  420.        struct bar {
  421.            short x, y;
  422.            char a, b;
  423.            int z;
  424.            struct bar * n;
  425.        };
  426.  
  427.        extern struct bar * my_struct;
  428.  
  429.        my_struct->x++;
  430.        my_struct->a = 5;
  431.        my_struct = my_struct->n;
  432.  
  433. corresponds to
  434.  
  435.        (def-c-struct bar
  436.          (x short)
  437.          (y short)
  438.          (a char)
  439.          (b char) ; or (b character) if it represents a character, not a number
  440.          (z int)
  441.          (n (c-ptr bar))
  442.        )
  443.  
  444.        (def-c-var my_struct (:type (c-ptr bar)))
  445.  
  446.        (setq my_struct (let ((s my_struct)) (incf (slot-value s 'x)) s))
  447.        or (incf (slot my_struct 'x))
  448.        (setq my_struct (let ((s my_struct)) (setf (slot-value s 'a) 5) s))
  449.        or (setf (slot my_struct 'a) 5)
  450.        (setq my_struct (slot-value my_struct 'n))
  451.        or (setq my_struct (deref (slot my_struct 'n)))
  452.  
  453. Ex. 3: An example for calling an external function:
  454. On ANSI C systems, <stdlib.h> contains the declarations
  455.  
  456.        typedef struct {
  457.          int quot;   /* Quotient */
  458.          int rem;    /* Remainder */
  459.        } div_t;
  460.        extern div_t div (int numer, int denom);
  461.  
  462. This translates to
  463.  
  464.        (def-c-struct div_t
  465.          (quot int)
  466.          (rem int)
  467.        )
  468.        (def-c-call-out div (:arguments (numer int) (denom int))
  469.                            (:return-type div_t)
  470.        )
  471.  
  472. Sample call from within Lisp:
  473.  
  474.        > (div 20 3)
  475.        #S(DIV :QUOT 6 :REM 2)
  476.  
  477. Ex. 4: Another example for calling an external function:
  478.  
  479. Suppose the following is defined in a file "cfun.c":
  480.  
  481.        struct cfunr { int x; char *s; };
  482.        struct cfunr * cfun (i,s,r,a)
  483.            int i;
  484.            char *s;
  485.            struct cfunr * r;
  486.            int a[10];
  487.        {
  488.            int j;
  489.            struct cfunr * r2;
  490.            printf("i = %d\n", i);
  491.            printf("s = %s\n", s);
  492.            printf("r->x = %d\n", r->x);
  493.            printf("r->s = %s\n", r->s);
  494.            for (j = 0; j < 10; j++) printf("a[%d] = %d.\n", j, a[j]);
  495.            r2 = (struct cfunr *) malloc (sizeof (struct cfunr));
  496.            r2->x = i+5;
  497.            r2->s = "A C string";
  498.            return r2;
  499.        }
  500.  
  501. It is possible to call this function from Lisp using the file "callcfun.lsp"
  502. (don't call it "cfun.lsp" - COMPILE-FILE would overwrite "cfun.c") whose
  503. contents is:
  504.  
  505.        (in-package "TEST-C-CALL" :use '("LISP" "FFI"))
  506.        (def-c-struct cfunr (x int) (s c-string))
  507.        (def-c-call-out cfun (:arguments (i int)
  508.                                         (s c-string)
  509.                                         (r (c-ptr cfunr) :in :alloca)
  510.                                         (a (c-ptr (c-array int 10)) :in :alloca)
  511.                             )
  512.                             (:return-type (c-ptr cfunr))
  513.        )
  514.        (defun call-cfun ()
  515.          (cfun 5 "A Lisp string" (make-cfunr :x 10 :s "Another Lisp string")
  516.                '#(0 1 2 3 4 5 6 7 8 9)
  517.        ) )
  518.  
  519. Use the module facility:
  520.  
  521.        $ clisp-link create-module-set cfun callcfun.c
  522.        $ cc -O -c cfun.c
  523.        $ cd cfun
  524.        $ ln -s ../cfun.o cfun.o
  525.        Add cfun.o to NEW_LIBS and NEW_FILES in link.sh.
  526.        $ cd ..
  527.        $ base/lisp.run -M base/lispinit.mem -c callcfun.lsp
  528.        $ clisp-link add-module-set cfun base base+cfun
  529.        $ base+cfun/lisp.run -M base+cfun/lispinit.mem -i callcfun
  530.        > (test-c-call::call-cfun)
  531.        i = 5
  532.        s = A Lisp string
  533.        r->x = 10
  534.        r->s = Another Lisp string
  535.        a[0] = 0.
  536.        a[1] = 1.
  537.        a[2] = 2.
  538.        a[3] = 3.
  539.        a[4] = 4.
  540.        a[5] = 5.
  541.        a[6] = 6.
  542.        a[7] = 7.
  543.        a[8] = 8.
  544.        a[9] = 9.
  545.        #S(TEST-C-CALL::CFUNR :X 10 :S "A C string")
  546.        > 
  547.        $ rm -r base+cfun
  548.  
  549. Note that there is a memory leak here: The return value r2 of cfun() is
  550. malloc()ed but never free()d. Specifying
  551.        (:return-type (c-ptr cfunr) :malloc-free)
  552. is not an alternative because this would also free(r2->x) but r2->x is a
  553. pointer to static data.
  554.  
  555. Ex. 5: To sort an array of double-floats using the Lisp function SORT
  556. instead of the C library function qsort(), one can use the following
  557. interface code "sort1.c". The main problem is to pass a variable-sized array.
  558.  
  559.        extern void lispsort_begin (int);
  560.        void* lispsort_function;
  561.        void lispsort_double (int n, double * array)
  562.        {
  563.            double * sorted_array;
  564.            int i;
  565.            lispsort_begin(n); /* store #'sort2 in lispsort_function */
  566.            sorted_array = ((double * (*) (double *)) lispsort_function) (array);
  567.            for (i = 0; i < n; i++) array[i] = sorted_array[i];
  568.            free(sorted_array);
  569.        }
  570.  
  571. This is accompanied by "sort2.lsp":
  572.  
  573.        (use-package "FFI")
  574.        (def-call-in lispsort_begin (:arguments (n int))
  575.                                    (:return-type nil)
  576.                                    (:language :stdc)
  577.        )
  578.        (def-c-var lispsort_function (:type c-pointer))
  579.        (defun lispsort_begin (n)
  580.          (setf (cast lispsort_function
  581.                      `(c-function
  582.                         (:arguments (v (c-ptr (c-array double-float ,n))))
  583.                         (:return-type (c-ptr (c-array double-float ,n))
  584.                                       :malloc-free
  585.                       ) )
  586.                )
  587.                #'sort2
  588.        ) )
  589.        (defun sort2 (v)
  590.          (declare (type vector v))
  591.          (sort v #'<)
  592.        )
  593.  
  594. To test this, use the following test file "sorttest.lsp":
  595.  
  596.        (def-call-out sort10
  597.                      (:name "lispsort_double")
  598.                      (:language :stdc)
  599.                      (:arguments (n int)
  600.                                  (array (c-ptr (c-array double-float 10))
  601.                                         :in-out
  602.        )             )           )
  603.  
  604. Now try
  605.  
  606.        $ clisp-link create-module-set sort sort2.c sorttest.c
  607.        $ cc -O -c sort1.c
  608.        $ cd sort
  609.        $ ln -s ../sort1.o sort1.o
  610.        Add sort1.o to NEW_LIBS and NEW_FILES in link.sh.
  611.        $ cd ..
  612.        $ base/lisp.run -M base/lispinit.mem -c sort2.lsp sorttest.lsp
  613.        $ clisp-link add-module-set sort base base+sort
  614.        $ base+sort/lisp.run -M base+sort/lispinit.mem -i sort2 sorttest
  615.        > (sort10 10 '#(0.501d0 0.528d0 0.615d0 0.550d0 0.711d0
  616.                        0.523d0 0.585d0 0.670d0 0.271d0 0.063d0))
  617.        #(0.063d0 0.271d0 0.501d0 0.523d0 0.528d0 0.55d0 0.585d0 0.615d0 0.67d0 0.711d0)
  618.        $ rm -r base+sort
  619.  
  620.