picolisp

Unnamed repository; edit this file to name it for gitweb.
git clone https://logand.com/git/picolisp.git/
Log | Files | Refs | README | LICENSE

native.html (27678B)


      1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/1998/REC-html40-19980424/loose.dtd">
      2 <html lang="en">
      3 <head>
      4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
      5 <title>Native C Calls</title>
      6 <link rel="stylesheet" href="doc.css" type="text/css">
      7 </head>
      8 <body>
      9 <a href="mailto:abu@software-lab.de">abu@software-lab.de</a>
     10 
     11 <h1>Native C Calls</h1>
     12 
     13 <p align=right>(c) Software Lab. Alexander Burger
     14 
     15 <p>This document describes how to call C functions in shared object files
     16 (libraries) from PicoLisp, using the built-in <code><a
     17 href="refN.html#native">native</a></code> function - possibly with the help of
     18 the <code><a href="refS.html#struct">struct</a></code> and <code><a
     19 href="refL.html#lisp">lisp</a></code> functions. It applies only to the 64-bit
     20 version of PicoLisp.
     21 
     22 <p><ul>
     23 <li><a href="#overview">Overview</a>
     24 <li><a href="#syntax">Syntax</a>
     25    <ul>
     26    <li><a href="#libs">Libraries</a>
     27    <li><a href="#funs">Functions</a>
     28    <li><a href="#retval">Return Value</a>
     29       <ul>
     30       <li><a href="#primRet">Primitive Types</a>
     31       <li><a href="#structRet">Arrays and Structures</a>
     32       </ul>
     33    <li><a href="#args">Arguments</a>
     34       <ul>
     35       <li><a href="#primArg">Primitive Types</a>
     36       <li><a href="#structArg">Arrays and Structures</a>
     37       </ul>
     38    </ul>
     39 <li><a href="#memory">Memory Management</a>
     40    <ul>
     41    <li><a href="#fftw">Fast Fourier Transform</a>
     42    <li><a href="#const">Constant Data</a>
     43    </ul>
     44 <li><a href="#callbacks">Callbacks</a>
     45    <ul>
     46    <li><a href="#byName">Call by Name</a>
     47    <li><a href="#funptr">Function Pointer</a>
     48    </ul>
     49 </ul>
     50 
     51 
     52 <p><hr>
     53 <h2><a name="overview">Overview</a></h2>
     54 
     55 <p><code>native</code> calls a C function in a shared library. It tries to
     56 
     57 <p><ol>
     58 <li>find a library by name
     59 <li>find a function by name in the library
     60 <li>convert the function's argument(s) from Lisp to C structures
     61 <li>call the function's C code
     62 <li>convert the function's return value(s) from C to Lisp structures
     63 </ol>
     64 
     65 <p>The direct return value of <code>native</code> is the Lisp representation of
     66 the C function's return value. Further values, returned by reference from the C
     67 function, are available in Lisp variables (symbol values).
     68 
     69 <p><code>struct</code> is a helper function, which can be used to manipulate C
     70 data structures in memory. It may take a scalar (a numeric representation of a C
     71 value) to convert it to a Lisp item, or (more typically) a pointer to a memory
     72 area to build and extract data structures. <code>lisp</code> allows you to
     73 install callback functions, callable from C code, written in Lisp.
     74 
     75 <p>In combination, these three functions can interface PicoLisp to almost any C
     76 function.
     77 
     78 <p>The above steps are fully dynamic; <code>native</code> doesn't have (and
     79 doesn't require) a priory knowledge about the library, the function or the
     80 involved data. No need to write any glue code, interfaces or include files. All
     81 functions can even be called interactively from the REPL.
     82 
     83 
     84 <p><hr>
     85 <h2><a name="syntax">Syntax</a></h2>
     86 
     87 <p>The arguments to <code>native</code> are
     88 
     89 <p><ol>
     90 <li>a library
     91 <li>a function
     92 <li>a return value specification
     93 <li>optional arguments
     94 </ol>
     95 
     96 <p>The simplest form is a call to a function without return value and without
     97 arguments. If we assume a library "lib.so", containing a function with the
     98 prototype
     99 
    100 <pre><code>
    101 void fun(void);
    102 </code></pre>
    103 
    104 <p>then we can call it as
    105 
    106 <pre><code>
    107 (native "lib.so" "fun")
    108 </code></pre>
    109 
    110 
    111 <p><hr>
    112 <h3><a name="libs">Libraries</a></h3>
    113 
    114 <p>The first argument to <code>native</code> specifies the library. It is either
    115 the <i>name</i> of a library (a symbol), or the <i>handle</i> of a previously
    116 found library (a number).
    117 
    118 <p>As a special case, a transient symbol <code>"@"</code> can be passed for the
    119 library name. It then refers to the current main program (instead of an external
    120 library), and can be used for standard functions like <code>"malloc"</code> or
    121 <code>"printf"</code>.
    122 
    123 <p><code>native</code> uses <code>dlopen(3)</code> internally to find and open
    124 the library, and to obtain the handle. If the name contains a slash ('/'), then
    125 it is interpreted as a (relative or absolute) pathname. Otherwise, the dynamic
    126 linker searches for the library according to the system's environment and
    127 directories. See the man page of <code>dlopen(3)</code> for further details.
    128 
    129 <p>If called with a symbolic argument, <code>native</code> automatically caches
    130 the handle of the found library in the value of that symbol. The most natural
    131 way is to pass the library name as a <a href="ref.html#transient">transient</a>
    132 symbol (<code>"lib.so"</code> above): The initial value of a transient symbol is
    133 that symbol itself, so that <code>native</code> receives the library name upon
    134 the first call. After successfully finding and opening the library,
    135 <code>native</code> stores the handle of that library in the value of the passed
    136 symbol (<code>"lib.so"</code>). As <code>native</code> evaluates its arguments
    137 in the normal way, subsequent calls within the same transient scope will receive
    138 the numeric value (the handle), and don't need to open and search the library
    139 again.
    140 
    141 
    142 <p><hr>
    143 <h3><a name="funs">Functions</a></h3>
    144 
    145 <p>The same rules applies to the second argument, the function. When called with
    146 a symbol, <code>native</code> stores the function pointer in its value, so that
    147 subsequent calls evaluate to that pointer, and <code>native</code> can directly
    148 jump to the function.
    149 
    150 <p><code>native</code> uses <code>dlsym(3)</code> internally to obtain the
    151 function pointer. See the man page of <code>dlsym(3)</code> for further details.
    152 
    153 <p>In most cases a program will call more than one function from a given
    154 library. If we keep the code within the same transient scope (i.e. in the same
    155 source file, and not separated by the <code><a
    156 href="ref_.html#====">====</a></code> function), each library will be opened -
    157 and each function searched - only once.
    158 
    159 <pre><code>
    160 (native "lib.so" "fun1")
    161 (native "lib.so" "fun2")
    162 (native "lib.so" "fun3")
    163 </code></pre>
    164 
    165 <p>After <code>"fun1"</code> was called, <code>"lib.so"</code> will be open, and
    166 won't be re-opened for <code>"fun2"</code> and <code>"fun3"</code>. Consider
    167 the definition of helper functions:
    168 
    169 <pre><code>
    170 (de fun1 ()
    171    (native "lib.so" "fun1") )
    172 
    173 (de fun2 ()
    174    (native "lib.so" "fun2") )
    175 
    176 (de fun3 ()
    177    (native "lib.so" "fun3") )
    178 </code></pre>
    179 
    180 <p>After any one of <code>fun1</code>, <code>fun2</code> or <code>fun3</code>
    181 was called, the symbol <code>"lib.so"</code> will hold the library handle. And
    182 each function function <code>"fun1"</code>, <code>"fun2"</code> and
    183 <code>"fun3"</code> will be searched only when called the first time.
    184 
    185 <p>Warning: It should be avoided to put more than one library into a single
    186 transient scope if there is a chance that two different functions with the same
    187 name will be called in two different libraries. Because of the function pointer
    188 caching, the second call would otherwise (wrongly) go to the first function.
    189 
    190 
    191 
    192 <p><hr>
    193 <h3><a name="retval">Return Value</a></h3>
    194 
    195 <p>The (optional) third argument to <code>native</code> specifies the return
    196 value. A C function can return many types of values, like integer or floating
    197 point numbers, string pointers, or pointers to structures which in turn consist
    198 of those types, and even other structures or pointers to structures.
    199 <code>native</code> tries to cover most of them.
    200 
    201 <p>As described in the <a href="refN.html#natResult">result specification</a>,
    202 the third argument should consist of a pattern which tells <code>native</code>
    203 how to extract the proper value.
    204 
    205 
    206 <h4><a name="primRet">Primitive Types</a></h4>
    207 
    208 <p>In the simplest case, the result specification is <code>NIL</code> like in
    209 the examples so far. This means that either the C function returns
    210 <code>void</code>, or that we are not interested in the value. The return value
    211 of <code>native</code> will be <code>NIL</code> in that case.
    212 
    213 <p>If the result specification is one of the symbols <code>B</code>,
    214 <code>I</code> or <code>N</code>, an integer number is returned, by interpreting
    215 the result as a <code>char</code> (8 bit unsigned byte), <code>int</code> (32
    216 bit signed integer), or <code>long</code> number (64 bit signed integer),
    217 respectively. Other (signed or unsigned numbers, and of different sizes) can be
    218 produced from these types with logical and arithmetic operations if necessary.
    219 
    220 <p>If the result specification is the symbol <code>C</code>, the result is
    221 interpreted as a 16 bit number, and a single-char transient symbol (string) is
    222 returned.
    223 
    224 <p>A specification of <code>S</code> tells <code>native</code> to interpret the
    225 result as a pointer to a C string (null terminated), and to return a transient
    226 symbol (string).
    227 
    228 <p>If the result specification is a number, it will be used as a scale to
    229 convert a returned <code>double</code> (if the number is positive) or
    230 <code>float</code> (if the number is negative) to a scaled fixpoint number.
    231 
    232 <p>Examples for function calls, with their corresponding C prototypes:
    233 
    234 <pre><code>
    235 (native "lib.so" "fun" 'I)             # int fun(void);
    236 (native "lib.so" "fun" 'N)             # long fun(void);
    237 (native "lib.so" "fun" 'N)             # void *fun(void);
    238 (native "lib.so" "fun" 'S)             # char *fun(void);
    239 (native "lib.so" "fun" 1.0)            # double fun(void);
    240 </code></pre>
    241 
    242 
    243 <h4><a name="structRet">Arrays and Structures</a></h4>
    244 
    245 <p>If the result specification is a list, it means that the C function returned
    246 a pointer to an array, or an arbitrary memory structure. The specification list
    247 should then consist of either the above primitive specifications (symbols or
    248 numbers), or of cons pairs of a primitive specification and a repeat count, to
    249 denote arrays of the given type.
    250 
    251 <p>Examples for function calls, with their corresponding pseudo C prototypes:
    252 
    253 <pre><code>
    254 (native "lib.so" "fun" '(I . 8))       # int *fun(void);  // 8 integers
    255 (native "lib.so" "fun" '(B . 16))      # unsigned char *fun(void);  // 16 bytes
    256 
    257 (native "lib.so" "fun" '(I I))         # struct {int i; int j;} *fun(void);
    258 (native "lib.so" "fun" '(I . 4))       # struct {int i[4];} *fun(void);
    259 
    260 (native "lib.so" "fun" '(I (B . 4)))   # struct {
    261                                        #    int i;
    262                                        #    unsigned char c[4];
    263                                        # } *fun(void);
    264 
    265 (native "lib.so" "fun"                 # struct {
    266    '(((B . 4) I) (S . 12) (N . 8)) )   #    struct {unsigned char c[4]; int i;}
    267                                        #    char *names[12];
    268                                        #    long num[8];
    269                                        # } *fun(void);
    270 </code></pre>
    271 
    272 <p>If a returned structure has an element which is a <i>pointer</i> to some
    273 other structure (i.e. not an embedded structure like in the last example above),
    274 this pointer must be first obtained with a <code>N</code> pattern, which can
    275 then be passed to <code><a href="refS.html#struct">struct</a></code> for further
    276 extraction.
    277 
    278 
    279 <p><hr>
    280 <h3><a name="args">Arguments</a></h3>
    281 
    282 <p>The (optional) fourth and following arguments to <code>native</code> specify
    283 the arguments to the C function.
    284 
    285 
    286 <h4><a name="primArg">Primitive Types</a></h4>
    287 
    288 <p>Integer arguments (up to 64 bits, signed or unsigned <code>char</code>,
    289 <code>short</code>, <code>int</code> or <code>long</code>) can be passed as they
    290 are: As numbers.
    291 
    292 <pre><code>
    293 (native "lib.so" "fun" NIL 123)        # void fun(int);
    294 (native "lib.so" "fun" NIL 1 2 3)      # void fun(int, long, short);
    295 </code></pre>
    296 
    297 <p>String arguments can be specified as symbols. <code>native</code> allocates
    298 memory for each string (with <code>strdup(3)</code>), passes the pointer to the
    299 C function, and releases the memory (with <code>free(3)</code>) when done.
    300 
    301 <pre><code>
    302 (native "lib.so" "fun" NIL "abc")      # void fun(char*);
    303 (native "lib.so" "fun" NIL 3 "def")    # void fun(int, char*);
    304 </code></pre>
    305 
    306 <p>Note that the allocated string memory is released <i>after</i> the return
    307 value is extracted. This allows a C function to return the argument string
    308 pointer, perhaps after modifying the data in-place, and receive the new string
    309 as the return value (with the <code>S</code> specification).
    310 
    311 <pre><code>
    312 (native "lib.so" "fun" 'S "abc")       # char *fun(char*);
    313 </code></pre>
    314 
    315 <p>Also note that specifying <code>NIL</code> as an argument passes an empty
    316 string ("", which also reads as <code>NIL</code> in PicoLisp) to the C function.
    317 Physically, this is a pointer to a NULL-byte, and is <u>not</u> a NULL-pointer.
    318 Be sure to pass <code>0</code> (the number zero) if a NULL-pointer is desired.
    319 
    320 <p>Floating point arguments are specified as cons pairs, where the value is in
    321 the CAR, and the CDR holds the fixpoint scale. If the scale is positive, the
    322 number is passed as a <code>double</code>, otherwise as a <code>float</code>.
    323 
    324 <pre><code>
    325 (native "lib.so" "fun" NIL             # void fun(double, float);
    326    (12.3 . 1.0) (4.56 . -1.0) )
    327 </code></pre>
    328 
    329 
    330 <h4><a name="structArg">Arrays and Structures</a></h4>
    331 
    332 <p>Composite arguments are specified as nested list structures.
    333 <code>native</code> allocates memory for each array or structure (with
    334 <code>malloc(3)</code>), passes the pointer to the C function, and releases the
    335 memory (with <code>free(3)</code>) when done.
    336 
    337 <p>This implies that such an argument can be both an input and an output value
    338 to a C function (pass by reference).
    339 
    340 <p>The CAR of the argument specification can be <code>NIL</code> (then it is an
    341 input-only argument). Otherwise, it should be a variable which receives the
    342 returned structure data.
    343 
    344 <p>The CADR of the argument specification must be a cons pair with the total
    345 size of the structure in its CAR. The CDR is ignored for input-only arguments,
    346 and should contain a <a href="refN.html#natResult">result specification</a> for
    347 the output value to be stored in the variable.
    348 
    349 <p>For example, a minimal case is a function that takes an integer reference,
    350 and stores the number '123' in that location:
    351 
    352 <pre><code>
    353 void fun(int *i) {
    354    *i = 123;
    355 }
    356 </code></pre>
    357 
    358 <p>We call <code>native</code> with a variable <code>X</code> in the CAR of the
    359 argument specification, a size of 4 (i.e. <code>sizeof(int)</code>), and
    360 <code>I</code> for the result specification. The stored value is then available
    361 in the variable <code>X</code>:
    362 
    363 <pre><code>
    364 : (native "lib.so" "fun" NIL '(X (4 . I)))
    365 -> NIL
    366 : X
    367 -> 123
    368 </code></pre>
    369 
    370 <p>The rest (CDDR) of the argument specification may contain initialization
    371 data, if the C function expects input values in the structure. It should be a
    372 list of <a href="refN.html#natItem">initialization items</a>, optionally with a
    373 fill-byte value in the CDR of the last cell.
    374 
    375 <p>If there are <i>no</i> initialization items and just the final fill-bye, then
    376 the whole buffer is filled with that byte. For example, to pass a buffer of 20
    377 bytes, initialized to zero:
    378 
    379 <pre><code>
    380 : (native "lib.so" "fun" NIL '(NIL (20) . 0))
    381 </code></pre>
    382 
    383 <p>A buffer of 20 bytes, with the first 4 bytes initialized to 1, 2, 3, and 4,
    384 and the rest filled with zero:
    385 
    386 <pre><code>
    387 : (native "lib.so" "fun" NIL '(NIL (20) 1 2 3 4 . 0))
    388 </code></pre>
    389 
    390 <p>and the same, where the buffer contents are returned as a list of bytes in
    391 the variable <code>X</code>:
    392 
    393 <pre><code>
    394 : (native "lib.so" "fun" NIL '(X (20 B . 20) 1 2 3 4 . 0))
    395 </code></pre>
    396 
    397 <p>For a more extensive example, let's use the following definitions:
    398 
    399 <pre><code>
    400 typedef struct value {
    401    int x, y;
    402    double a, b, c;
    403    int z;
    404    char nm[4];
    405 } value;
    406 
    407 void fun(value *val) {
    408    printf("%d %d\n", val->x, val->y);
    409    val->x = 3;
    410    val->y = 4;
    411    strcpy(val->nm, "OK");
    412 }
    413 </code></pre>
    414 
    415 <p>We call this function with a structure of 40 bytes, requesting the returned
    416 data in <code>V</code>, with two integers <code>(I . 2)</code>, three doubles
    417 <code>(100 . 3)</code> with a scale of 2 (1.0 = 100), another integer
    418 <code>I</code> and four characters <code>(C . 2)</code>. If the structure gets
    419 initialized with two integers 7 and 6, three doubles 0.11, 0.22 and 0.33, and
    420 another integer 5 while the rest of the 40 bytes is cleared to zero
    421 
    422 <pre><code>
    423 : (native "lib.so" "fun" NIL
    424    '(V (40 (I . 2) (100 . 3) I (C . 4)) -7 -6 (100 11 22 33) -5 . 0) )
    425 </code></pre>
    426 
    427 <p>then it will print the integers 7 and 6, and <code>V</code> will contain the
    428 returned list
    429 
    430 <pre><code>
    431 ((3 4) (11 22 33) 5 ("O" "K" NIL NIL))
    432 </code></pre>
    433 
    434 <p>i.e. the original integer values 7 and 6 replaced with 3 and 4.
    435 
    436 <p>Note that the allocated structure memory is released <i>after</i> the return
    437 value is extracted. This allows a C function to return the argument structure
    438 pointer, perhaps after modifying the data in-place, and receive the new
    439 structure as the return value - instead of (or even in addition to) to the
    440 direct return via the argument reference.
    441 
    442 
    443 <p><hr>
    444 <h2><a name="memory">Memory Management</a></h2>
    445 
    446 <p>The preceding <a href="#args">Arguments</a> section mentions that
    447 <code>native</code> implicitly allocates and releases memory for strings, arrays
    448 and structures.
    449 
    450 <p>Technically, this mimics <i>automatic variables</i> in C.
    451 
    452 <p>For a simple example, let's assume that we want to call <code>read(2)</code>
    453 directly, to fetch a 4-byte integer from a given file descriptor. This could be
    454 done with the following C function:
    455 
    456 <pre><code>
    457 int read4bytes(int fd) {
    458    char buf[4];
    459 
    460    read(fd, buf, 4);
    461    return *(int*)buf;
    462 }
    463 </code></pre>
    464 
    465 <p><code>buf</code> is an automatic variable, allocated on the stack, which
    466 disappears when the function returns. A corresponding <code>native</code> call
    467 would be:
    468 
    469 <pre><code>
    470 (native "@" "read" 'N Fd '(Buf (4 . I)) 4)
    471 </code></pre>
    472 
    473 <p>The structure argument <code>(Buf (4 . I))</code> says that a space of 4
    474 bytes should be allocated and passed to <code>read</code>, then an integer
    475 <code>I</code> returned in the variable <code>Buf</code> (the return value of
    476 <code>native</code> itself is the number returned by <code>read</code>). The
    477 memory space is released after that.
    478 
    479 <p>(Note that we use <code>"@"</code> for the library here, as <code>read</code>
    480 resides in the main program.)
    481 
    482 <p>Instead of a single integer, we might want a list of four bytes to be
    483 returned from <code>native</code>:
    484 
    485 <pre><code>
    486 (native "@" "read" 'N Fd '(Buf (4 B . 4)) 4)
    487 </code></pre>
    488 
    489 <p>The difference is that we wrote <code>(B . 4)</code> (a list of 4 bytes)
    490 instead of <code>I</code> (a single integer) for the <a
    491 href="refN.html#natResult">result specification</a> (see the <a
    492 href="#structArg">Arrays and Structures</a> section).
    493 
    494 <p>Let's see what happens if we extend this example. We'll write the four bytes
    495 to another file descriptor, after reading them from the first one:
    496 
    497 <pre><code>
    498 void copy4bytes(int fd1, int fd2) {
    499    char buf[4];
    500 
    501    read(fd1, buf, 4);
    502    write(fd2, buf, 4);
    503 }
    504 </code></pre>
    505 
    506 <p>Again, <code>buf</code> is an automatic variable. It is passed to both
    507 <code>read</code> and <code>write</code>. A direct translation would be:
    508 
    509 <pre><code>
    510 (native "@" "read" 'N Fd '(Buf (4 B . 4)) 4)
    511 (native "@" "write" 'N Fd (cons NIL (4) Buf) 4)
    512 </code></pre>
    513 
    514 <p>This work as expected. <code>read</code> returns a list of four bytes in
    515 <code>Buf</code>. The call to <code>cons</code> builds the structure
    516 
    517 <pre><code>
    518 (NIL (4) 1 2 3 4)
    519 </code></pre>
    520 
    521 <p>i.e. no return variable, a four-byte memory area, filled with the four bytes
    522 (assuming that <code>read</code> returned 1, 2, 3 and 4). Then this structure is
    523 passed to <code>write</code>.
    524 
    525 <p>But: This solution induces quite some overhead. The four-byte buffer is
    526 allocated before the call to <code>read</code> and released after that, then
    527 allocated and released again for <code>write</code>. Also, the bytes are
    528 converted to a list to be stored in <code>Buf</code>, then that list is extended
    529 for the structure argument to <code>write</code>, and converted again back to
    530 the raw byte array. The data in the list itself are never used.
    531 
    532 <p>If the above operation is to be used more than once, it is better to allocate
    533 the buffer manually, use it for both reading and writing, and then release it.
    534 This also avoids all intermediate list conversions.
    535 
    536 <pre><code>
    537 (let Buf (native "@" "malloc" 'N 4) # Allocate memory
    538    (native "@" "read" 'N Fd Buf 4)  # (Possibly repeat this several times)
    539    (native "@" "write" 'N Fd Buf 4)
    540    (native "@" "free" NIL Buf) )    # Release memory
    541 </code></pre>
    542 
    543 
    544 <h4><a name="fftw">Fast Fourier Transform</a></h4>
    545 
    546 <p>For a more typical example, we might call the Fast Fourier Transform using
    547 the library from the <a href="http://fftw.org">FFTW</a> package. With the
    548 example code for calculating Complex One-Dimensional DFTs:
    549 
    550 <pre><code>
    551 #include &lt;fftw3.h&gt;
    552 ...
    553 {
    554    fftw_complex *in, *out;
    555    fftw_plan p;
    556    ...
    557    in = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * N);
    558    out = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * N);
    559    p = fftw_plan_dft_1d(N, in, out, FFTW_FORWARD, FFTW_ESTIMATE);
    560    ...
    561    fftw_execute(p); /* repeat as needed */
    562    ...
    563    fftw_destroy_plan(p);
    564    fftw_free(in); fftw_free(out);
    565 }
    566 </code></pre>
    567 
    568 <p>we can build the following equivalent:
    569 
    570 <pre><code>
    571 (load "@lib/math.l")
    572 
    573 (de FFTW_FORWARD . -1)
    574 (de FFTW_ESTIMATE . 64)
    575 
    576 (de fft (Lst)
    577    (let
    578       (Len (length Lst)
    579          In (native "libfftw3.so" "fftw_malloc" 'N (* Len 16))
    580          Out (native "libfftw3.so" "fftw_malloc" 'N (* Len 16))
    581          P (native "libfftw3.so" "fftw_plan_dft_1d" 'N
    582             Len In Out FFTW_FORWARD FFTW_ESTIMATE ) )
    583       (struct In NIL (cons 1.0 (apply append Lst)))
    584       (native "libfftw3.so" "fftw_execute" NIL P)
    585       (prog1 (struct Out (make (do Len (link (1.0 . 2)))))
    586          (native "libfftw3.so" "fftw_destroy_plan" NIL P)
    587          (native "libfftw3.so" "fftw_free" NIL Out)
    588          (native "libfftw3.so" "fftw_free" NIL In) ) ) )
    589 </code></pre>
    590 
    591 <p>This assumes that the argument list <code>Lst</code> is passed as a list
    592 of complex numbers, each as a list of two numbers for the real and imaginary
    593 part, like
    594 
    595 <pre><code>
    596 (fft '((1.0 0) (1.0 0) (1.0 0) (1.0 0) (0 0) (0 0) (0 0) (0 0)))
    597 </code></pre>
    598 
    599 <p>The above translation to Lisp is quite straightforward. After the two buffers
    600 are allocated, and a plan is created, <code><a
    601 href="refS.html#struct">struct</a></code> is called to store the argument list
    602 in the <code>In</code> structure as a list of double numbers (according to the
    603 <code>1.0</code> <a href="refN.html#natItem">initialization item</a>). Then
    604 <code>fftw_execute</code> is called, and <code>struct</code> is called again to
    605 retrieve the result from <code>Out</code> and return it from <code>fft</code>
    606 via the <code><a href="refP.html#prog1">prog1</a></code>. Finally, all memory is
    607 released.
    608 
    609 
    610 <h4><a name="const">Constant Data</a></h4>
    611 
    612 <p>If such allocated data (strings, arrays or structures passed to
    613 <code>native</code>) are constant during the lifetime of a program, it makes
    614 sense to allocate them only once, before their first use. A typical candidate is
    615 the format string of a <code>printf</code> call. Consider a function which
    616 prints a floating point number in scientific notation:
    617 
    618 <pre><code>
    619 (load "@lib/math.l")
    620 
    621 : (de prf (Flt)
    622    (native "@" "printf" NIL "%e^J" (cons Flt 1.0)) )
    623 -> prf
    624 
    625 : (prf (exp 12.3))
    626 2.196960e+05
    627 </code></pre>
    628 
    629 <p>As we know that the format string <code>"%e^J"</code> will be converted from
    630 a Lisp symbol to a C string with <code>strdup</code> - and then thrown away - on
    631 each call to <code>prf</code>, we might as well perform a little optimization
    632 and delegate this conversion to the program load time:
    633 
    634 <pre><code>
    635 : (de prf (Flt)
    636    (native "@" "printf" NIL `(native "@" "strdup" 'N "%e^J") (cons Flt 1.0)) )
    637 -> prf
    638 
    639 : (prf (exp 12.3))
    640 2.196960e+05
    641 </code></pre>
    642 
    643 <p>If we look at the <code>prf</code> function, we see that it now contains the
    644 pointer to the allocated string memory:
    645 
    646 <pre><code>
    647 : (pp 'prf)
    648 (de prf (Flt)
    649    (native "@" "printf" NIL 24662032 (cons Flt 1000000)) )
    650 -> prf
    651 </code></pre>
    652 
    653 <p>This pointer will be used by <code>printf</code> directly, without any
    654 further conversion or memory management.
    655 
    656 
    657 <p><hr>
    658 <h2><a name="callbacks">Callbacks</a></h2>
    659 
    660 <p>Sometimes it is necessary to do the reverse: Call Lisp code from C code. This
    661 can be done in two ways - with certain limitations.
    662 
    663 
    664 <h4><a name="byName">Call by Name</a></h4>
    665 
    666 <p>The first way is actually not a <a
    667 href="http://en.wikipedia.org/wiki/Callback_(computer_programming)">callback</a>
    668 in the strict sense. It just allows to call a Lisp function with a given name.
    669 
    670 <p>The limitation is that this function can accept only maximally five numeric
    671 arguments, and returns a number.
    672 
    673 <p>The prerequisite is, of course, that you have access to the C source code. To
    674 use it from C, insert the following prototype somewhere before the first call:
    675 
    676 <pre><code>
    677 long lisp(char*,long,long,long,long,long);
    678 </code></pre>
    679 
    680 <p>Then you can call <code>lisp</code> from C:
    681 
    682 <pre><code>
    683 long n = lisp("myLispFun", a, b, 0, 0, 0);
    684 </code></pre>
    685 
    686 <p>The first argument should be the name of a Lisp function (built-in, or
    687 defined in Lisp). It is searched for at runtime, so it doesn't need to exist at
    688 the time the C library is compiled or loaded.
    689 
    690 <p>Be sure to pass dummy arguments (e.g. zero) if your function expects less
    691 than five arguments, to keep the C compiler happy.
    692 
    693 <p>This mechanism can generally be used for any type of argument and return
    694 value (not only <code>long</code>). On the C side, appropriate casts or a
    695 adapted prototype should be used. It is then up to the called Lisp function to
    696 prepare and/or extract the proper data with <code><a
    697 href="refS.html#struct">struct</a></code> and memory management operations.
    698 
    699 
    700 <h4><a name="funptr">Function Pointer</a></h4>
    701 
    702 <p>This is a true <a
    703 href="http://en.wikipedia.org/wiki/Callback_(computer_programming)">callback</a>
    704 mechanism. It uses the Lisp-level function <code><a
    705 href="refL.html#lisp">lisp</a></code> (not to confuse with the C-level function
    706 with the same name in the previous section). No C source code access is
    707 required.
    708 
    709 <p><code>lisp</code> returns a function pointer, which can be passed to C
    710 functions via <code>native</code>. When this function pointer is dereferenced
    711 and called from the C code, the corresponding Lisp function is invoked. Here,
    712 too, only five numeric arguments and a numeric return value can be used, and
    713 other data types must be handled by the Lisp function with <code><a
    714 href="refS.html#struct">struct</a></code> and memory management operations.
    715 
    716 <p>Callbacks are often used in user interface libraries, to handle key-, mouse-
    717 and other events. Examples can be found in <code>"@lib/openGl.l"</code>. The
    718 following function <code>mouseFunc</code> takes a Lisp function, installs it
    719 under the tag <code>mouseFunc</code> (any other tag would be all right too) as a
    720 callback, and passes the resulting function pointer to the OpenGL
    721 <code>glutMouseFunc()</code> function, to set it as a callback for the current
    722 window:
    723 
    724 <pre><code>
    725 (de mouseFunc (Fun)
    726    (native `*GlutLib "glutMouseFunc" NIL (lisp 'mouseFunc Fun)) )
    727 </code></pre>
    728 
    729 <p>(The global <code>*GlutLib</code> holds the library
    730 <code>"/usr/lib/libglut.so"</code>. The backquote (<code>`</code>) is important
    731 here, so that the transient symbol with the library name (and not the global
    732 <code>*GlutLib</code>) is evaluated by <code>native</code>, resulting in the
    733 proper library handle at runtime).
    734 
    735 <p>A program using OpenGL may then use <code>mouseFunc</code> to install a
    736 function
    737 
    738 <pre><code>
    739 (mouseFunc
    740    '((Btn State X Y)
    741       (do-something-with Btn State X Y) ) )
    742 </code></pre>
    743 
    744 <p>so that future clicks into the window will pass the button, state and
    745 coordinates to that function.
    746 
    747 </body>
    748 </html>