Initial git import
[sxemacs] / info / lispref / ffi.texi
1 @c -*-texinfo-*-
2 @c This is part of the SXEmacs Lisp Reference Manual.
3 @c Copyright (C) 2005 Sebastian Freundt <hroptatyr@sxemacs.org>
4 @c Copyright (C) 2005 Zajcev Evgeny <lg@xwem.org>
5 @c See the file lispref.texi for copying conditions.
6 @setfilename ../../info/ffi.info
7
8 @node Foreign Functions, MULE, Internationalization, Top
9 @chapter Foreign Function Interface (FFI)
10 @cindex FO
11 @cindex FFI
12 @cindex foreign objects
13 @cindex foreign functions
14
15 @macro FFI
16 FFI
17 @end macro
18
19   The SXEmacs @dfn{Foreign Function Interface} (@FFI{} for short) adds
20 support for invoking code written in other programming languages from
21 within elisp.  The @FFI{} focuses on interaction with C code, but the
22 basic framework can also be used for interfacing to languages other
23 than C, provided they support to be compiled to binary and linked into
24 a @dfn{shared library}.
25
26   The SXEmacs @FFI{} can access sharable object files at runtime and
27 use their definition without relocating or relinking the SXEmacs
28 binary.  The purpose (and main motivation) therefore clearly is to
29 supply elisp programmers with a convenient way to implement features
30 from underlying libraries without even touching the C level.
31
32   The @FFI{} feature itself must be considered experimental, though.
33 It is a lot of effort to secure raw library calls from misuse,
34 especially because the SXEmacs error handler has no influence on the
35 events triggered inside of the foreign library.  On the other hand,
36 keeping foreign function calls under exhaustive surveillance would
37 noticably slow down the @FFI{}, if not even limit the capabilities at
38 all.
39
40 @menu
41 * Basic C Types and Functions:: Default type and function bindings
42                                   from the Standard C library (libc)
43 * Calling Foreign Functions::   How to call functions defined in an
44                                   external library.
45 * Examining and Modifying::     How to examine and modify foreign
46                                   objects.
47 * User-Defined Types::          How to reflect custom type definitions
48                                   in an external library.
49 * ffi-curl::                    FFI-bindings for the libcurl library.
50 * ffi-wand::                    FFI-bindings for the libWand library.
51 @end menu
52
53
54 @node Basic C Types and Functions
55 @section Basic C Types and Functions
56
57   In order to provide a convenient way to access the standard C
58 library (libc), FFI comes with a set of predefined types and
59 functions.  Of course, you can access other functions and define other
60 types beside the ones in libc.  The discussion here is intended to be
61 a basic introduction to FFI.  To use a specific library see the more
62 general sections @ref{Calling Foreign Functions} and @ref{User-Defined
63 Types}.
64
65 @menu
66 * Predefined FFI data types::   A list of predefined, ready-to-go
67                                   types provided by FFI.
68 * The pointer form::    A type modifier to reference data.
69 * The function form::   A type modifier to reference functions.
70 * The array form::      A type modifier to specify arrays.
71 * The union form::      A type modifier to specify unions.
72 * The struct form::     A type modifier to specify stuctures.
73 * The c-data form::     A type modifier to specify memory blocks.
74 * FFI type-related functions::  Functions to gather information on types.
75 @end menu
76
77 @node Predefined FFI data types
78 @subsection Predefined FFI data types
79
80   The following assortment lists all predefined C data types.  These
81 types are also known as Basic FFI types.  We assume these to be well
82 known and do not explain them further.
83
84 @itemize
85 @item
86 @code{byte}, @code{unsigned byte}
87 @item
88 @code{char}, @code{unsigned-char}
89 @item
90 @code{short}, @code{unsigned-short}
91 @item
92 @code{int}, @code{unsigned-int}
93 @item
94 @code{long}, @code{unsigned-long}
95 @item
96 @code{float},
97 @item
98 @code{double}
99 @item
100 @code{void}
101 @item
102 @code{c-string}
103 @item
104 @code{c-data}
105 @end itemize
106
107   As with C data types, the actual meaning of these types depends on
108 the system architecture, but there is no difference between these FFI
109 predefined types and their C-pendant if FFI is run on the same
110 machine.
111
112   However, the last two types in the list are special in that they are
113 actually a @code{(pointer char)} (in C known as @samp{char*}), but (as
114 the name suggests) data of this type form a string on C level, or
115 arbitrary chunks of (bytewise-oriented) data which is translated to or
116 translated from an ordinary emacs string.  In constrast, we should
117 mention that the @samp{char*} is actually solely a pointer to one
118 character, and @emph{not} a string a priori.
119
120   In order to handle arbitrary binary data blocks, the type
121 @code{c-data} can be used in conjunction with a size parameter (see
122 The @code{c-data} form).  Strings -- the internal representation
123 of data of this type -- are (re-)encoded to @code{binary} (i.e. the
124 generic binary coding system) due to Mule issues.
125
126
127 @node The pointer form
128 @subsection The @code{pointer} form
129 @cindex pointer FFI type-modifier
130
131   As mentioned in the previous section, every data type can be
132 pointerised, that is create another FFI-object with the address of the
133 data (not the data itself).  We say such data @dfn{point to} other
134 data.
135
136   The syntax for this is the form @code{'(pointer @var{data-type})},
137 so for example the FFI-type @code{'(pointer int)} is the data type
138 @samp{int*} in C.
139
140
141 @node The function form
142 @subsection The @code{function} form
143 @cindex function FFI type-modifier
144
145   In addition to pointerised data, there is a special type modifier to
146 represent function signatures.  Such type-cells are needed to declare
147 function objects.
148
149   The syntax for this is the form @code{'(function @var{return-type}
150 @var{arg1-type} @dots{} @var{argn-type})}, so for example
151 the FFI-type @code{'(function int int unsigned-int)} would be
152 rewritten in C as @samp{int some_undefined_name(int, unsigned int)}.
153
154   The return type and at least one argument type are mandatory!  So
155 the syntax for functions without return values, i.e. procedures, is to
156 pass the type @samp{void} as return type.  Similarly, pass a
157 @samp{void} as arg1-type for functions without arguments.
158
159
160 @node The array form
161 @subsection The @code{array} form
162 @cindex array FFI type-modifier
163
164   Arrays in general are finite, indexed sets of unityped data.  That
165 is (informally), a contiguous piece of memory with data slots, where
166 the data slots all have the same type and are enumerated from 0 to
167 @code{size-1}.  Accessing a certain slot is achieved by passing its
168 slot number to the accessor function.
169
170   The syntax for this type-modification is the form
171 @code{'(array @var{type} @var{size})}, with size being a positive
172 integer.  For example the FFI-type @code{'(array int 20)} would be
173 equivalent to the C-syntax @samp{int some_undefined_name[20]}.
174
175
176 @node The union form
177 @subsection The @code{union} form
178 @cindex union FFI type-modifier
179
180   Unions in general are mutually exclusive variants of data types
181 which are united into a super-type.  More formally, the data in a
182 union is a component projection of a product of many types.
183 Informally, the union is a choice of one datum and (with it) one type
184 at a time out of many ones.  Unions are arranged by named slots of
185 different types.  The slots are accessed by their names.
186
187 @noindent
188 The syntax for this type-modification is the form:
189 @example
190 '(union @var{name}
191   (@var{slot-name1} @var{type1})
192   @dots{}
193   (@var{slot-namen} @var{typen}))
194 @end example
195
196
197 @node The struct form
198 @subsection The @code{struct} form
199 @cindex struct FFI type-modifier
200
201   Structures in general are products of other types.  Structures
202 consist of named data slots of different types.  The slots are
203 accessed by their names.
204
205 @noindent
206 The syntax for this type-modification is the form:
207 @example
208 '(struct @var{name}
209   (@var{slot-name1} @var{type1})
210   @dots{}
211   (@var{slot-namen} @var{typen}))
212 @end example
213
214
215 @node The c-data form
216 @subsection The @code{c-data} form
217
218   C-data in general is hard to describe, it is everything which is a
219 contiguous piece of memory, called a block of memory.  Data of this
220 type is represented byte-wise, the internal representation is an emacs
221 string encoded as @code{binary}.
222
223   The syntax is a cons-cell with the symbol @code{c-data} in the car
224 and a non-negative integer in the cdr.  For a (yet) unknown length of
225 a data block one can simply use the non-cons'd version @code{'c-data}.
226
227 @example
228 @group
229 ;; block of 40 bytes of arbitrary data
230 '(c-data . 40)
231 @end group
232 @group
233 ;; indefinite block of data
234 'c-data
235 @end group
236 @end example
237
238 @c   The @code{unknown} symbol may be used if the size of a memory block
239 @c is yet unknown or may vary.  Fetching data from or pumping data to an
240 @c indefinitely sized foreign object is not possible.  Instead, the
241 @c object should be type-cast for reading and writing operations.
242
243
244 @node FFI type-related functions
245 @subsection FFI type-related functions
246
247 @c probably we should unify our documentation, sometimes it's `foreign
248 @c type' sometimes it's `FFI type' etc.
249
250 @defun ffi-basic-type-p type
251 Return non-@code{nil} if @var{type} is a basic FFI type.
252
253 A type is said to be basic, if it is neither a pointer nor a
254 function, and there is a corresponding built-in type in C.
255 @end defun
256
257 @defun ffi-type-p type &optional signal-p
258 Return non-@code{nil} if @var{type} is a valid FFI type.
259 If optional argument @var{signal-p} is non-@code{nil} and @var{type}
260 is not an FFI type, additionally signal an error.
261 @end defun
262
263 @defvar ffi-type-checker [defaults to: @code{ffi-type-p}]
264 Function to call when the validity of an FFI type shall be checked.
265 @end defvar
266
267 @defvar ffi-named-types
268 Alist of named FFI types with elements of the form 
269 @code{(NAME . FFI-TYPE)}.
270 @end defvar
271
272 @defun ffi-size-of-type type
273 Return the size of the foreign type @var{type}.
274
275 Valid foreign types are: @samp{byte}, @samp{unsigned-byte},
276 @samp{char}, @samp{unsigned-char}, @samp{short},
277 @samp{unsigned-short}, @samp{int}, @samp{unsigned-int}, @samp{long},
278 @samp{unsigned-long}, @samp{pointer-void}, @samp{float},
279 @samp{double}, @samp{object}, and @samp{c-string}.
280 @end defun
281
282 @defun ffi-fixup-type type
283 Return FFI type @var{type} in a canonical form.
284 @end defun
285
286 @defun ffi-set-storage-size fo size
287 Set the size of the allocated space of @var{fo} to @var{size}.
288 @end defun
289
290
291
292 @node Calling Foreign Functions
293 @section Calling Foreign Functions
294
295   Calling FFI functions is a many-step process.  The actual call of an
296 external function is the last step in this chain but can be done
297 repeatedly and almost as comfortable as elisp function calls
298 thenceforth.  The chain to FFI function calls can be summed up as
299 following.
300
301 @enumerate
302 @item
303 incorporate external library contents
304 @item
305 declare function signatures
306 @item
307 initialise function arguments
308 @item
309 call the function
310 @end enumerate
311
312   Hereby, step 1 is independent from the other steps.  It can be
313 interchanged with the other steps arbitrarily, but is mandatory at
314 all.
315
316 @subsection Incorporate External Library Contents
317
318 @defun ffi-load libname
319 Load library @var{libname}.
320 Return a foreign object handle if successful, or indicate an error if
321 the library cannot be loaded.
322
323 The argument @var{libname} should be the file-name string of a shared
324 object library (usual extension is @file{.so}).
325
326 The library should reside in one of the directories specified by the
327 @var{$LD_LIBRARY_PATH} environment variable or the more global
328 @file{ld.so.cache}.
329 @end defun
330
331   Note you cannot simply modify the @file{ld.so.cache}, instead use the
332 command @code{ldconfig} on a suited configuration file.  See your
333 vendor's documentation how to do that.
334
335   Loading a library using @code{ffi-load} additionally registers this
336 library in a list of already loaded libraries.
337
338 @defvar ffi-loaded-libraries
339 Alist of loaded libraries with elements of the form @code{(LIB-NAME . FFIO)}.
340 @end defvar
341
342   There is a raw library loader function without the registration code
343 and without error handling.  However, it is highly suggested to use
344 @code{ffi-load} exclusively.
345
346 @defun ffi-load-library libname
347 Load library @var{libname}.
348 Return a foreign object handle if successful, or @code{nil} if the
349 library cannot be loaded.
350
351 The argument @var{libname} should be the file-name string of a shared
352 object library (usual extension is @file{.so}).
353
354 The library should reside in one of the directories specified by the
355 @var{$LD_LIBRARY_PATH} environment variable or the more global
356 @file{ld.so.cache}.
357 @end defun
358
359   The following example (like all other examples in this section) is
360 taken from @file{ffi-curl.el} which comes with the SXEmacs
361 distribution.  We assume the library @file{libcurl.so} to exist and to
362 reside in a directory searched by the dynamic loader.
363
364 @example
365 (ffi-load "libcurl.so")
366      @result{} #<ffiobject type=(pointer void) size=4 fotype=2
367      foptr=0x8a1dad8>
368 ffi-loaded-libraries
369      @result{} (("libcurl.so" . #<ffiobject type=(pointer void) size=4 fotype=2 foptr=0x8a1dad8>))
370 @end example
371
372
373 @subsection Declaring Function Signatures
374
375   Declaring the signature of a function is quite like reading a
376 library's include file.  The main function to achieve this is
377 @code{ffi-defun}.
378
379 @defun ffi-defun type sym
380 Make and return a foreign object of type @var{type} and bind it to the
381 external symbol @var{sym}.
382
383 The argument @var{type} should be a function type-cell.
384 The argument @var{sym} should be a string naming a function in one of
385 the loaded libraries.
386
387 If @var{sym} does not exist in any of the loaded libraries, an error
388 is indicated.
389
390 This is like @code{ffi-bind} but for function objects.
391 @end defun
392
393   On the other hand, a library may contain useful variables.  The main
394 directive to bind such variable objects is @code{ffi-bind}.
395
396 @defun ffi-bind type sym
397 Make and return a foreign object of type @var{type} and bind it to the
398 external symbol @var{sym}.
399
400 The argument @var{type} can be any type-cell.
401 The argument @var{sym} should be a string naming an arbitrary symbol
402 in one of the loaded libraries.
403
404 If @var{sym} does not exist in any of the loaded libraries, @code{nil}
405 is returned.
406 @end defun
407
408 @noindent
409 Again, let's look at an example taken from @file{ffi-curl.el}
410
411 @example
412 (setq curl:curl_easy_getinfo
413       (ffi-defun '(function int (pointer void) int) "curl_easy_getinfo"))
414      @result{} #<ffiobject type=(function int (pointer void) int) size=4 fotype=3 foptr=0x40bfa370>
415 @end example
416
417 @noindent
418 The @code{ffi-bind} function works similarly.
419
420
421 @subsection Initialising Function Arguments
422
423   As seen in the previous example, external objects are assigned an
424 (elisp-)internal object which refers to them.  Following this
425 abstraction process, it is kind of obvious that arguments for external
426 functions cannot be passed as internal elisp objects, but have to be
427 converted somehow.
428
429   The most user-friendly function to accomplish this task is
430 @code{ffi-create-fo}, although it cannot catch all the cases
431 (especially compound types are missing as of November 2005).
432
433 @defun ffi-create-fo type val
434 Create a foreign object of type @var{type} and set its value to
435 @var{val}.  Return created FFI object.
436 @end defun
437
438   Note that memory allocation and other administrative tasks are
439 entirely performed within the FFI API without involving the user.
440 That is why we can simply ``convert'' an elisp string to a C string,
441 as the example below will demonstrate.
442
443 @example
444 @group
445 (ffi-create-fo 'c-string "foobar")
446      @result{} #<ffiobject type=c-string size=4 fotype=0 foptr=0x88e3fdc>
447 @end group
448 @group
449 (ffi-create-fo 'unsigned-int 2299)
450      @result{} #<ffiobject type=unsigned-int size=4 fotype=0 foptr=0x89f648c>
451 @end group
452 @end example
453
454   The function @code{ffi-create-fo} is written in lisp and decomposes
455 to more elementary functions.  We are going to discuss them here
456 flatly since they provide a more sophisticated basis for the handling
457 of foreign objects.
458
459 @defun make-ffi-object type &optional size
460 Create a new FFI object of type @var{type}.
461 If optional argument @var{size} is non-@code{nil} it should be an
462 integer, in this case additional storage size to hold data of at
463 least length @var{size} is allocated.
464 @end defun
465
466 @defun ffi-set fo val
467 Set @var{fo}'s foreign value to @var{val}.
468 @end defun
469
470   Note that currently @code{ffi-set} does @emph{not} work on compound
471 data types, nevertheless there are workaround functions.
472
473   The following example will demonstrate the use of
474 @code{make-ffi-object} and, in conjunction, @code{ffi-set}.
475
476 @example
477 @group
478 (setq xmpl-fo (make-ffi-object 'long))
479      @result{} #<ffiobject type=long size=4 fotype=0 foptr=0x8937dcc>
480 (ffi-set xmpl-fo 20000)
481      @result{} 20000
482 xmpl-fo
483      @result{} #<ffiobject type=long size=4 fotype=0 foptr=0x8937dcc>
484 @end group
485
486 @group
487 (setq xmpl-fo (make-ffi-object 'c-string))
488      @result{} #<ffiobject type=c-string size=4 fotype=0 foptr=0x890158c>
489 (ffi-set xmpl-fo "some test string")
490      @result{} "some test string"
491 xmpl-fo
492      @result{} #<ffiobject type=c-string size=4 fotype=0 foptr=0x890158c>
493 (ffi-get xmpl-fo)
494      @result{} "some test string"
495 @end group
496 @end example
497
498   After using @code{make-ffi-object} to create foreign objects,
499 @emph{always} make sure that these were assigned a value before
500 requesting the object's data, or simply always use
501 @code{ffi-create-fo}.  In the former case, FFI does not initialise the
502 object with default data, its value is therefore indefinite and may
503 cause a crash of SXEmacs when queried.
504
505   Also, check carefully to only assign data which is suited for the
506 underlying C type.  Passing, for example, strings to
507 @samp{unsigned-int}s or @samp{long} values to an object of type
508 @samp{int} may not only result in unexpected behaviour but almost
509 certainly a crash.
510
511   Like @code{ffi-create-fo} the function @code{ffi-set} is a higher
512 level lisp binding.  It decomposes into several raw FFI API functions
513 which are presented here just for completeness.  It is highly advised
514 to exclusively use @code{ffi-set}.
515
516 @defun ffi-store fo offset val-type val
517 Store and return the value @var{val} of type @var{val-type} in
518 @var{fo}'s foreign space at @var{offset}.
519
520 @var{val-type} can be either a basic FFI type or an FFI pointer.
521 If @var{val-type} is a basic FFI type, then @var{val} can be an
522 ordinary, but suitable Emacs lisp object.
523 If @var{val-type} is an FFI pointer then @var{val} @emph{must} be an
524 FFI object of the underlying type pointed to.
525 @end defun
526
527
528 @subsection Calling Functions
529
530   Now that function signatures are bound and argument data is
531 initialised, we can dare to actually apply functions and operations on
532 our data.  The main function to achieve this is
533 @code{ffi-call-function}.
534
535 @defun ffi-call-function fo &rest args
536 Call a function referred to by @var{fo} with arguments @var{args},
537 maybe return a foreign object with the result or @code{nil} if there
538 is none.
539
540 @var{fo} should be a binding initiated by @code{ffi-defun}, and
541 @var{args} should be foreign data objects or pointers to these.
542 @end defun
543
544   Unlike with most Emacs lisp functional bindings foreign functions
545 can be called by reference, this means a function may be passed a
546 foreign object as argument and the function's result will reside in
547 that foreign object.
548
549   Before we come to an example, we shall discuss two further functions
550 which ``re-convert'' foreign object data to internal Emacs lisp data.
551
552 @defun ffi-get fo &keys type off
553 Return @var{fo}'s value (converted to Emacs lisp compliant form).
554
555 Optional key @var{:type} may be used to cast @var{fo} to @var{:type},
556 it defaults to the object's assigned type.
557 Optional key @var{:off} may be used to specify an offset, it defaults
558 to 0.
559 @end defun
560
561   The backbone function of @code{ffi-get} is @code{ffi-fetch}, but it
562 is highly advised to exclusively use @code{ffi-get}, which in contrast
563 also works for structs, arrays and pointers.
564
565 @defun ffi-fetch fo offset type
566 Return @var{fo}'s value (converted to Emacs lisp compliant form).
567 @var{fo} is cast to @var{type}, and the value is aligned to
568 @var{offset}.
569 @end defun
570
571
572 @noindent
573 Let us now look at the promised example.
574
575 @example
576 (ffi-load "libcurl.so")
577      @result{} #<ffiobject type=(pointer void) size=4 fotype=2 foptr=0x8a1cc78>
578
579 ;; we want: char *curl_escape(const char *string, int length);
580 ;; this function takes a usual string and returns a version suitable
581 ;; as URI
582 (setq curl:curl_escape
583       (ffi-defun '(function c-string c-string int) "curl_escape"))
584      @result{} #<ffiobject type=(function c-string c-string int) size=4 fotype=3 foptr=0x40bf2e50>
585
586 ;; now prepare the funcall
587 (let* ((url "http://foo.org/please escape this<$!=3>")
588        (str (ffi-create-fo 'c-string url))
589        (len (ffi-create-fo 'int (length url))))
590   ;; call the function
591   (setq result (ffi-call-function curl:curl_escape str len)))
592      @result{} #<ffiobject type=c-string size=4 fotype=0 foptr=0x8906af8>
593
594 ;; now let's see what the escaped form is
595 (ffi-get result)
596      @result{} "http%3A%2F%2Ffoo%2Eorg%2Fplease%20escape%20this%3C%24%21%3D3%3E"
597
598 ;; and compare to
599 (ffi-get result :off 13)
600      @result{} "foo%2Eorg%2Fplease%20escape%20this%3C%24%21%3D3%3E"
601
602 ;; and to
603 (ffi-get result :type 'char)
604      @result{} ?h
605 @end example
606
607
608 @c   The whole procedure of binding foreign function objects can be
609 @c abbreviated using the macro @code{define-ffi-function}.
610 @c 
611 @c @c all in one macro
612 @c @defvr Macro define-ffi-function fsym args doc-string ftype ename
613 @c 
614 @c @end defvr
615
616
617
618 @node Examining and Modifying
619 @section Examining and Modifying Foreign Objects
620
621   In this section we give a quick overview of what else can be done
622 with foreign objects or foreign function definitions.
623
624 @c on objects and their types
625 @defun ffi-object-p fo
626 Return non-@code{nil} if @var{fo} is an FFI object, nil otherwise.
627 @end defun
628 @defun ffi-object-type fo
629 Return @var{fo}'s type.
630 @end defun
631 @defun ffi-set-object-type fo type
632 Cast @var{fo} to type @var{type} and reassign the cast value.
633 @end defun
634
635 @c on objects and their data
636 @defun ffi-object-size fo
637 Return the size of the allocated space of @var{fo}.
638 @end defun
639
640 @defun ffi-set-storage-size fo size
641 Set the size of the allocated space of @var{fo} to @var{size}.
642 @end defun
643
644 @defun ffi-address-of fo
645 Return the FFI object that stores address of given FFI object
646 @var{fo}.
647
648 This is the equivalent of the @samp{&} operator in C.
649 @end defun
650 @defun ffi-deref fo-pointer
651 Return the data @var{fo-pointer} points to.
652
653 This is the equivalent of the `*' operator in C.
654 @end defun
655 @defun ffi-null-p fo
656 Return non-@code{nil} if @var{fo} is a null pointer, @code{nil}
657 otherwise.
658 Non-@code{nil} may be returned only for pointer types or the type
659 @samp{c-string}.
660 @end defun
661 @defun ffi-null-pointer
662 Return the FFI object that represents a null pointer.
663
664 This is the equivalent of @samp{NULL} in C.
665 @end defun
666
667
668   For foreign arrays, unions and structures, there are accessor
669 functions to modify or fetch portions in the foreign object: 
670
671 @c on foreign arrays
672 @defun ffi-aref farray idx
673 Return the element of @var{farray} at index @var{idx}.
674 The slot enumeration starts at 0.
675 @end defun
676 @defun ffi-aset farray idx value
677 Store the element @var{value} in @var{farray} at index @var{idx}.
678 The slot enumeration starts at 0.
679 @end defun
680
681 @defun ffi-slot-offset type slot
682 Return the offset of @var{slot} in @var{type}.
683 @var{slot} can be either a valid (named) slot in @var{type} or
684 @code{nil}.
685 If @var{slot} is @code{nil} return the size of the structure.
686 @end defun
687
688 @example
689 (define-ffi-type mystruct
690   (struct foo
691    (bar int)
692    (hey char)
693    (baz c-string)))
694 (ffi-slot-offset 'mystruct 'baz)
695      @result{} 8
696 @end example
697
698
699 @c @defun ffi-dlerror
700 @c @end defun
701 @c 
702 @c @defun ffi-plist
703 @c @end defun
704
705
706
707 @node User-Defined Types
708 @section User-Defined Types
709 @cindex user-defined types
710
711   As usual in most libraries written in C, objects carry an abstract
712 type.  These abstract types can be aliases for the built-in ones,
713 @samp{struct}s or @samp{union}s composed by more atomic types.
714
715   For the bare aliasing of types, there is a macro
716 @code{define-ffi-type}, which can also be used to construct unions, as
717 well as arrays.
718
719 @defvr Macro define-ffi-type name type
720 Associate @var{name} with FFI @var{type}.  When defining global
721 structures or unions, @var{name} may be @code{nil}, in that case
722 @var{name} is derived from the name of @var{type}.
723 @end defvr
724
725 @example
726 (define-ffi-type mytype unsigned-long)
727      @result{} mytype
728 @end example
729
730   Once a type is defined that way, it can be used as if it was a
731 native C-type.
732
733 @example
734 (ffi-type-p 'mytype)
735      @result{} t
736 (ffi-size-of-type 'mytype)
737      @result{} 4
738 @end example
739
740 @noindent
741 As mentioned above, we look at the construction of arrays now.
742
743 @example
744 (define-ffi-type myarray (array unsigned-long 8))
745      @result{} myarray
746 (ffi-size-of-type 'myarray)
747      @result{} 32
748 @end example
749
750   Similarly, unions and structs can be defined.  For structs, however,
751 there exists a more dedicated definition function,
752 @code{define-ffi-struct}.  This function also defines setter and
753 getter forms which can be used to selectively set or get the slots in
754 a structure.
755
756   Getting the value of a slot in a structure defined that way can be
757 done with a function @code{@var{structname}->@var{slotname}}.  Setting
758 values is achieved by using @code{setf} on
759 @code{@var{structname}->@var{slotname}}.
760
761 @defvr Macro define-ffi-struct name &rest slots
762 Define a new structure of NAME and SLOTS.
763 @end defvr
764
765 @example
766 (define-ffi-struct foo (sl1 unsigned-int) (sl2 char) (sl3 int))
767      @result{} (lambda (obj) "
768 Common Lisp lambda list:
769   (foo->sl3 OBJ)
770
771 " (block foo->sl3 (let* ((--obj--temp-- (gensym "--obj--"))
772 (--nv--temp-- (gensym "--nv--"))) (list (list --obj--temp--) (list
773 obj) (list --nv--temp--) (let* ((obj --obj--temp--) (nv --nv--temp--))
774 (list (quote ffi-store) obj (list (quote ffi-slot-offset) (quote
775 (quote foo)) (quote (quote sl3))) (list (quote ffi-slot-type) (quote
776 (quote foo)) (quote (quote sl3))) nv)) (list (quote foo->sl3)
777 --obj--temp--)))))
778 (fboundp #'foo->sl1)
779      @result{} t
780 (fboundp #'foo->sl2)
781      @result{} t
782 (fboundp #'foo->sl2)
783      @result{} t
784 @end example
785
786
787 @subsection Enumerations
788 @cindex enumerations
789
790 A special case of user-defined data are so called enumerations.
791 Basically they are used to simultaneously define a large block of
792 aliases.  These are enumerated (beginning from 0) and are replaced by
793 the according integers during the preprocessor time.
794
795 For convenience the SXEmacs FFI interface provides a similar
796 functionality.
797
798 @defvr Macro ffi-enum name &optional docstring &rest specs
799 Define an enumeration @var{name}.
800 Optional argument @var{docstring} is a documentation string.
801
802 @var{specs} can be an arbitrary number of symbols which will be
803 enumerated in the respective order.
804
805 Additionally the cells of @var{specs} may look like
806
807 @samp{  foo = bar}
808
809 to adhere a symbol @samp{foo} to the enumeration with the value of the
810 symbol @samp{bar} (i.e. @samp{foo} is an alias of @samp{bar}).
811
812 Moreover, it is possible to set the counter explicitly:
813
814 @samp{  baz = 5}
815
816 would assign a value of 5 to the symbol @samp{baz} and (by side-effect)
817 set the counter to 6 for the next symbol.
818
819 The defined enumeration will result in a (@code{defconst}'d) variable
820 @code{name}, the value is an alist of the form 
821
822 @samp{  ((symbol . value) ...)},
823
824 where @samp{value} is the C-value of @samp{symbol}.
825
826 Furthermore, two functions (named @code{@var{name}} and
827 @code{@var{name}-value}) will be defined.  The first one is a simple
828 lookup function returning the C-value of a passed symbol.  The second
829 does basically the same but returns the representing (elisp) integer of
830 a symbol.  Both functions return @code{nil} if the symbol is not in the
831 enumeration.
832 @end defvr
833
834
835
836
837
838 @node ffi-curl
839 @section FFI-bindings for libcurl
840 @cindex ffi-curl.el
841 @cindex libcurl
842
843   The next passages introduce bindings defined on top of the current
844 FFI implementation.  To conceal the poorly conceived documentation of
845 FFI itself we strongly advertise to work out the whole power of FFI by
846 these example application.
847
848   cURL is a command line tool for transferring files with URL syntax,
849 supporting FTP, FTPS, TFTP, HTTP, HTTPS, GOPHER, TELNET, DICT, FILE
850 and LDAP.  cURL supports HTTPS certificates, HTTP POST, HTTP PUT, FTP
851 uploading, HTTP form based upload, proxies, cookies, user+password
852 authentication (Basic, Digest, NTLM, Negotiate, kerberos, @dots{}), file
853 transfer resume, proxy tunneling and a busload of other useful tricks.
854
855   The cURL-API is, like cURL itself, free and open software.  The main
856 entrance to cURL is the curl-easy interface, which ffi-curl.el intends
857 to implement.
858
859   The FFI-bindings for libcurl can be classified roughly into guts and
860 main procedures (there is actually only one main procedure).  However,
861 we discuss the guts of the API now.
862
863 @subsection Low-level functions of @file{ffi-curl.el}
864
865   As usual, the function's communication takes place via contextes,
866 hence any of the cURL functions expect a context handle which is
867 initially produced by @code{curl:easy-init}.
868
869 @defun curl:easy-init
870 Initialise curl easy interface and return a context handle.
871 @end defun
872
873 @defun curl:easy-cleanup ctx
874 Clean up context @var{ctx} and free resources allocated with it.
875 This function must be called after every easy session.
876 @end defun
877
878 @noindent
879 Remember to always free all requested context handles.  The garbage
880 collector of SXEmacs has no influence on them nor on their allocated
881 memory.
882
883 @example
884 (let ((context (curl:easy-init)))
885   (curl:easy-cleanup context))
886      @result{} nil
887 @end example
888
889
890   Having allocated a context handle all cURL functions use it by
891 reference, that is functions change it by side-effect or magically
892 retrieve values from it.
893
894 @defun curl:easy-setopt ctx &rest options
895 Set @var{options} for curl transfer in session @var{ctx}.
896
897 Options are passed as keyword-value-pairs. Supported keywords are:
898 @itemize
899 @item
900 @code{:url} @samp{string} --
901 a valid Uniform Resource Locator.
902 @item
903 @code{:fstream} @samp{ffi-fo} --
904 a file descriptor to which output is redirected.
905 @item
906 @end itemize
907 @end defun
908
909 @defun curl:easy-perform ctx
910 Perform cURL operation on the context @var{ctx}.
911
912 To control the behaviour of the session or set options into the
913 context, see @code{curl:easy-setopt}.
914 @end defun
915
916 @defun curl:easy-getinfo ctx what
917 Get info from the context @var{ctx} about @var{what}.
918 @end defun
919
920 @defvr Constant curl:errors-alist
921 Alist of error codes and associated clear-text error messages.
922 @end defvr
923
924
925 @subsection User-level functions of @file{ffi-curl.el}
926
927   All of the prior routines have been used to define a user-level
928 function which can be used without the need to deal with the
929 internals.
930
931 @defun curl:download url file &rest options
932 Download the contents @var{url} to and write them to @var{file}.
933 Return 0 on success or an integer specifying an error code.
934
935 Optionally you can specify keywords in @var{options}.
936 The options are keyword-value-pairs and are set via
937 @code{curl:easy-setopt}.
938 @end defun
939
940 @example
941 (curl:download "http://www.sxemacs.org" 
942   (expand-file-name (make-temp-name "curl") (temp-directory)))
943      @result{} 0
944 @end example
945
946
947
948 @node ffi-wand
949 @section FFI-bindings for libWand
950 @cindex ffi-wand.el
951 @cindex libWand
952
953   The libWand library is the proposed API to the ImageMagick core.
954 Depending on the configuration of ImageMagick it supports many, many
955 different file formats for input and output and comes along with a
956 powerful set of image manipulation commands.
957
958   Just like the bindings for libcurl the libWand bindings can be
959 roughly classified into user-level functions and commands, currently
960 there is only one command in this class, and low-level API calls.
961
962 @subsection Low-level functions of @file{ffi-wand.el}
963
964 @c @defvr FFI-type MagickWand 
965 @c A context.
966 @c 
967 @c An alias for '(pointer void).
968 @c @end defvr
969 @c 
970 @c @defvr FFI-type MagickBooleanType
971 @c A boolean type for function return values.
972 @c 
973 @c An alias for 'long.
974 @c @end defvr
975 @c 
976 @c @defvr FFI-type MagickStorageType
977 @c Type for the enumeration of storage methods.
978 @c 
979 @c An alias for 'unsigned-long.
980 @c @end defvr
981 @c 
982 @c @defvr FFI-type MagickChannelType
983 @c Type for the enumeration of channels.
984 @c 
985 @c An alias for 'unsigned-long.
986 @c @end defvr
987
988 @noindent
989 Let us begin with context handlers.
990
991 @defun Wand:make-wand
992 Return a newly allocated MagickWand (the context handle of libWand).
993 @end defun
994
995 @defun Wand:clear-wand wand
996 Clear all resources associated with the @var{wand}.
997 This does not free the memory, i.e. @var{wand} can furtherly be used
998 as a context, see @code{Wand:delete-wand}.
999 @end defun
1000
1001 @defun Wand:copy-wand wand
1002 Return a cloned copy of @var{wand}.
1003 This duplicates everything necessary to get an exact, but independent
1004 clone of @var{wand}.
1005 @end defun
1006
1007 @defun Wand:delete-wand wand
1008 Delete the @var{wand}.
1009 This frees all resources associated with the @var{wand}.
1010
1011 WARNING: Do not use @var{wand} after calling this function!
1012 @end defun
1013
1014 @defun Wand:wandp wand
1015 Return non-@code{nil} if @var{wand} is a magick wand, @code{nil}
1016 otherwise.
1017 @end defun
1018
1019 @example
1020 (setq foo (Wand:make-wand))
1021      @result{} #<ffiobject type=MagickWand size=4 fotype=0 foptr=0x8b38350>
1022 (Wand:wandp foo)
1023      @result{} t
1024 (Wand:delete-wand foo)
1025      @result{} nil
1026 (Wand:wandp foo)
1027      @result{} nil
1028 @end example
1029
1030
1031 @subsection Input/Output functions of Wand context handles
1032
1033 @noindent
1034 Now here is an assortment of functions which operate on a Wand.
1035
1036 @c input/output
1037 @defun Wand:read-image wand file
1038 Read @var{file} and associate it with @var{wand}.
1039 @end defun
1040
1041 @defun Wand:write-image wand file
1042 Write the image associated with @var{wand} to @var{file}.
1043 @end defun
1044
1045 @defun Wand:display-image wand
1046 Display the image associated with @var{wand}.
1047 @end defun
1048
1049 @defun Wand:get-image-pixels-internal wand from-width from-height delta-width delta-height
1050 Return a raw string of image pixel data (RGB triples).
1051 @end defun
1052
1053 @defun Wand:get-image-pixels wand
1054 Return a raw string of image pixel data (RGB triples).
1055 @end defun
1056
1057
1058 @subsection Image geometry and canvas functions
1059
1060 @c geometry and canvas
1061 @defun Wand:get-image-height wand
1062 Return the height of the image in @var{wand} in pixels.
1063 @end defun
1064 @defun Wand:get-image-width wand
1065 Return the width of the image in @var{wand} in pixels.
1066 @end defun
1067
1068 @defun Wand:scale-image wand width height
1069 Scale the image in @var{wand} to the dimensions @var{width} times
1070 @var{height}.
1071 @end defun
1072
1073 @defun Wand:crop-image wand x y dx dy
1074 Crop to the rectangle spanned at coordinates (@var{x}, @var{y}) by
1075 width @var{dx} and height @var{dy} in the image associated with
1076 @var{wand}.
1077 @end defun
1078
1079 @defun Wand:flip-image wand
1080 Mirror the image associated with @var{wand} around the x-axis.
1081 @end defun
1082 @defun Wand:flop-image wand
1083 Mirror the image associated with @var{wand} around the y-axis.
1084 @end defun
1085
1086 @defun Wand:roll-image wand x y
1087 Rolls (offsets) the image associated with @var{wand} to an offset of
1088 @var{x} and @var{y}.
1089 @end defun
1090
1091
1092 @subsection Image refinement functions
1093
1094 @c image improvements
1095 @defun Wand:increase-contrast-image wand
1096 Increase the contrast of the image associated with @var{wand}.
1097 @end defun
1098 @defun Wand:decrease-contrast-image wand
1099 Decrease the contrast of the image associated with @var{wand}.
1100 @end defun
1101
1102 @defun Wand:despeckle-image wand
1103 Reduce the speckle noise in the image associated with @var{wand}.
1104 @end defun
1105
1106 @defun Wand:enhance-image wand
1107 Enhance the image associated with @var{wand}.
1108 @end defun
1109
1110 @defun Wand:equalize-image wand
1111 Equalise the image associated with @var{wand}.
1112 @end defun
1113
1114 @defun Wand:normalize-image wand
1115 Normalise the image associated with @var{wand}.
1116 @end defun
1117
1118 @defun Wand:reduce-noise-image wand radius
1119 Reduce the noise in the image associated with @var{wand}.
1120 @end defun
1121
1122
1123 @defun Wand:posterize-image wand levels &optional ditherp
1124 Posterize the image associated with @var{wand},
1125 that is quantise the range of used colours to at most @var{levels}.
1126 If optional argument @var{ditherp} is non-@code{nil} use a dithering
1127 effect to wipe hard contrasts.
1128 @end defun
1129
1130 @defun Wand:gamma-image wand level
1131 Perform gamma correction on the image associated with @var{wand}.
1132 The argument @var{level} is a positive float, a value of 1.00 
1133 (read 100%) is a no-op.
1134 @end defun
1135
1136 @defun Wand:median-filter-image wand radius
1137 Perform median normalisation of the pixels in the image associated
1138 with @var{wand}.
1139 @end defun
1140
1141 @defun Wand:solarize-image wand threshold
1142 Solarise the image associated with @var{wand}.
1143 @end defun
1144
1145 @defun Wand:modulate-image wand brightness saturation hue
1146 Tweak the image associated with @var{wand}.
1147 @end defun
1148
1149 @defun Wand:negate-image wand &optional greyp
1150 Perform negation on the image associated with @var{wand}.
1151 @end defun
1152
1153
1154 @subsection Image effects functions
1155
1156 @c effects
1157 @defun Wand:charcoal-image wand radius sigma
1158 Simulate a charcoal drawing of the image associated with @var{wand}.
1159 The @var{radius} argument is a float and measured in pixels.
1160 The @var{sigma} argument is a float and defines a derivation.
1161 @end defun
1162
1163 @defun Wand:oil-paint-image wand radius
1164 Simulate oil-painting of image associated with @var{wand}.
1165 The @var{radius} argument is a float and measured in pixels.
1166 @end defun
1167
1168 @defun Wand:edge-image wand radius
1169 Enhance the edges of the image associated with @var{wand}.
1170 The @var{radius} argument is a float and measured in pixels.
1171 @end defun
1172
1173 @defun Wand:emboss-image wand radius sigma
1174 Emboss the image associated with @var{wand} (a relief effect).
1175 The @var{radius} argument is a float and measured in pixels.
1176 The @var{sigma} argument is a float and defines a derivation.
1177 @end defun
1178
1179 @defun Wand:wave-image wand amplitude wavelength
1180 Create a ripple effect on the image associated with @var{wand}.
1181 The @var{amplitude} argument is a float and defines the how large
1182 waves are.
1183 The @var{wavelength} argument is a float and defines how often the
1184 waves occur.
1185 @end defun
1186
1187
1188 @subsection Image blurring and sharpening functions
1189
1190 @c blurs
1191 @defun Wand:blur-image wand radius sigma
1192 Blur the image associated with @var{wand}.
1193 The @var{radius} argument is a float and measured in pixels.
1194 The @var{sigma} argument is a float and defines a derivation.
1195 @end defun
1196
1197 @defun Wand:gaussian-blur-image wand radius sigma
1198 Blur the image associated with @var{wand}.
1199 The @var{radius} argument is a float and measured in pixels.
1200 The @var{sigma} argument is a float and defines a derivation.
1201 @end defun
1202
1203 @defun Wand:motion-blur-image wand radius sigma angle
1204 Blur the image associated with @var{wand}.
1205 The @var{radius} argument is a float and measured in pixels.
1206 The @var{sigma} argument is a float and defines a derivation.
1207 The @var{angle} argument is a float and measured in degrees.
1208 @end defun
1209
1210 @defun Wand:radial-blur-image wand angle
1211 Blur the image associated with @var{wand}.
1212 The @var{angle} argument is a float and measured in degrees.
1213 @end defun
1214
1215 @defun Wand:sharpen-image wand radius sigma
1216 Sharpen the image associated with @var{wand}.
1217 The @var{radius} argument is a float and measured in pixels.
1218 The @var{sigma} argument is a float and defines a derivation.
1219 @end defun
1220
1221 @defun Wand:unsharp-mask-image wand radius sigma amount threshold
1222 Sharpen the image associated with @var{wand} using an unsharp mask.
1223 The unsharp mask is defined by @var{radius} and @var{sigma} (defined
1224 as in @code{Wand:blur-image}).
1225 The strength of sharpening is controlled by @var{amount} and
1226 @var{threshold}.
1227 @end defun
1228
1229
1230
1231 @subsection User-level functions of @file{ffi-wand.el}
1232
1233   Mostly, for demonstration purposes, there are two functions which
1234 are claimed to be suitable for user interaction.  The only operations
1235 they perform are reading an image file, rescaling it to fit into the
1236 window, glyphifying it and to insert that glyph into a buffer.
1237
1238 @defun Wand:show-image-file-here file
1239 Insert a glyph with the image from @var{file} at current point,
1240 scale image to fit the buffer window if necessary.
1241 @end defun
1242
1243 @defun Wand:show-image-file file
1244 Insert a glyph with the image from @var{file} in a dedicated buffer,
1245 scale image to fit the buffer window if necessary.
1246 @end defun
1247
1248
1249
1250 @c ffi.texi ends here