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
8 @node Foreign Functions, MULE, Internationalization, Top
9 @chapter Foreign Function Interface (FFI)
12 @cindex foreign objects
13 @cindex foreign functions
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}.
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.
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
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
45 * Examining and Modifying:: How to examine and modify foreign
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.
54 @node Basic C Types and Functions
55 @section Basic C Types and Functions
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
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.
77 @node Predefined FFI data types
78 @subsection Predefined FFI data types
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.
86 @code{byte}, @code{unsigned byte}
88 @code{char}, @code{unsigned-char}
90 @code{short}, @code{unsigned-short}
92 @code{int}, @code{unsigned-int}
94 @code{long}, @code{unsigned-long}
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
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.
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.
127 @node The pointer form
128 @subsection The @code{pointer} form
129 @cindex pointer FFI type-modifier
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
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
141 @node The function form
142 @subsection The @code{function} form
143 @cindex function FFI type-modifier
145 In addition to pointerised data, there is a special type modifier to
146 represent function signatures. Such type-cells are needed to declare
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)}.
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.
161 @subsection The @code{array} form
162 @cindex array FFI type-modifier
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.
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]}.
177 @subsection The @code{union} form
178 @cindex union FFI type-modifier
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.
188 The syntax for this type-modification is the form:
191 (@var{slot-name1} @var{type1})
193 (@var{slot-namen} @var{typen}))
197 @node The struct form
198 @subsection The @code{struct} form
199 @cindex struct FFI type-modifier
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.
206 The syntax for this type-modification is the form:
209 (@var{slot-name1} @var{type1})
211 (@var{slot-namen} @var{typen}))
215 @node The c-data form
216 @subsection The @code{c-data} form
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}.
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}.
229 ;; block of 40 bytes of arbitrary data
233 ;; indefinite block of data
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.
244 @node FFI type-related functions
245 @subsection FFI type-related functions
247 @c probably we should unify our documentation, sometimes it's `foreign
248 @c type' sometimes it's `FFI type' etc.
250 @defun ffi-basic-type-p type
251 Return non-@code{nil} if @var{type} is a basic FFI type.
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.
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.
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.
267 @defvar ffi-named-types
268 Alist of named FFI types with elements of the form
269 @code{(NAME . FFI-TYPE)}.
272 @defun ffi-size-of-type type
273 Return the size of the foreign type @var{type}.
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}.
282 @defun ffi-fixup-type type
283 Return FFI type @var{type} in a canonical form.
286 @defun ffi-set-storage-size fo size
287 Set the size of the allocated space of @var{fo} to @var{size}.
292 @node Calling Foreign Functions
293 @section Calling Foreign Functions
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
303 incorporate external library contents
305 declare function signatures
307 initialise function arguments
312 Hereby, step 1 is independent from the other steps. It can be
313 interchanged with the other steps arbitrarily, but is mandatory at
316 @subsection Incorporate External Library Contents
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.
323 The argument @var{libname} should be the file-name string of a shared
324 object library (usual extension is @file{.so}).
326 The library should reside in one of the directories specified by the
327 @var{$LD_LIBRARY_PATH} environment variable or the more global
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.
335 Loading a library using @code{ffi-load} additionally registers this
336 library in a list of already loaded libraries.
338 @defvar ffi-loaded-libraries
339 Alist of loaded libraries with elements of the form @code{(LIB-NAME . FFIO)}.
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.
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.
351 The argument @var{libname} should be the file-name string of a shared
352 object library (usual extension is @file{.so}).
354 The library should reside in one of the directories specified by the
355 @var{$LD_LIBRARY_PATH} environment variable or the more global
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.
365 (ffi-load "libcurl.so")
366 @result{} #<ffiobject type=(pointer void) size=4 fotype=2
369 @result{} (("libcurl.so" . #<ffiobject type=(pointer void) size=4 fotype=2 foptr=0x8a1dad8>))
373 @subsection Declaring Function Signatures
375 Declaring the signature of a function is quite like reading a
376 library's include file. The main function to achieve this is
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}.
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.
387 If @var{sym} does not exist in any of the loaded libraries, an error
390 This is like @code{ffi-bind} but for function objects.
393 On the other hand, a library may contain useful variables. The main
394 directive to bind such variable objects is @code{ffi-bind}.
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}.
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.
404 If @var{sym} does not exist in any of the loaded libraries, @code{nil}
409 Again, let's look at an example taken from @file{ffi-curl.el}
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>
418 The @code{ffi-bind} function works similarly.
421 @subsection Initialising Function Arguments
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
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).
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.
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.
445 (ffi-create-fo 'c-string "foobar")
446 @result{} #<ffiobject type=c-string size=4 fotype=0 foptr=0x88e3fdc>
449 (ffi-create-fo 'unsigned-int 2299)
450 @result{} #<ffiobject type=unsigned-int size=4 fotype=0 foptr=0x89f648c>
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
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.
466 @defun ffi-set fo val
467 Set @var{fo}'s foreign value to @var{val}.
470 Note that currently @code{ffi-set} does @emph{not} work on compound
471 data types, nevertheless there are workaround functions.
473 The following example will demonstrate the use of
474 @code{make-ffi-object} and, in conjunction, @code{ffi-set}.
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)
483 @result{} #<ffiobject type=long size=4 fotype=0 foptr=0x8937dcc>
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"
492 @result{} #<ffiobject type=c-string size=4 fotype=0 foptr=0x890158c>
494 @result{} "some test string"
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.
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
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}.
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}.
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.
528 @subsection Calling Functions
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}.
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
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.
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
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.
552 @defun ffi-get fo &keys type off
553 Return @var{fo}'s value (converted to Emacs lisp compliant form).
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
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.
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
573 Let us now look at the promised example.
576 (ffi-load "libcurl.so")
577 @result{} #<ffiobject type=(pointer void) size=4 fotype=2 foptr=0x8a1cc78>
579 ;; we want: char *curl_escape(const char *string, int length);
580 ;; this function takes a usual string and returns a version suitable
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>
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))))
591 (setq result (ffi-call-function curl:curl_escape str len)))
592 @result{} #<ffiobject type=c-string size=4 fotype=0 foptr=0x8906af8>
594 ;; now let's see what the escaped form is
596 @result{} "http%3A%2F%2Ffoo%2Eorg%2Fplease%20escape%20this%3C%24%21%3D3%3E"
599 (ffi-get result :off 13)
600 @result{} "foo%2Eorg%2Fplease%20escape%20this%3C%24%21%3D3%3E"
603 (ffi-get result :type 'char)
608 @c The whole procedure of binding foreign function objects can be
609 @c abbreviated using the macro @code{define-ffi-function}.
611 @c @c all in one macro
612 @c @defvr Macro define-ffi-function fsym args doc-string ftype ename
618 @node Examining and Modifying
619 @section Examining and Modifying Foreign Objects
621 In this section we give a quick overview of what else can be done
622 with foreign objects or foreign function definitions.
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.
628 @defun ffi-object-type fo
629 Return @var{fo}'s type.
631 @defun ffi-set-object-type fo type
632 Cast @var{fo} to type @var{type} and reassign the cast value.
635 @c on objects and their data
636 @defun ffi-object-size fo
637 Return the size of the allocated space of @var{fo}.
640 @defun ffi-set-storage-size fo size
641 Set the size of the allocated space of @var{fo} to @var{size}.
644 @defun ffi-address-of fo
645 Return the FFI object that stores address of given FFI object
648 This is the equivalent of the @samp{&} operator in C.
650 @defun ffi-deref fo-pointer
651 Return the data @var{fo-pointer} points to.
653 This is the equivalent of the `*' operator in C.
656 Return non-@code{nil} if @var{fo} is a null pointer, @code{nil}
658 Non-@code{nil} may be returned only for pointer types or the type
661 @defun ffi-null-pointer
662 Return the FFI object that represents a null pointer.
664 This is the equivalent of @samp{NULL} in C.
668 For foreign arrays, unions and structures, there are accessor
669 functions to modify or fetch portions in the foreign object:
672 @defun ffi-aref farray idx
673 Return the element of @var{farray} at index @var{idx}.
674 The slot enumeration starts at 0.
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.
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
685 If @var{slot} is @code{nil} return the size of the structure.
689 (define-ffi-type mystruct
694 (ffi-slot-offset 'mystruct 'baz)
699 @c @defun ffi-dlerror
707 @node User-Defined Types
708 @section User-Defined Types
709 @cindex user-defined types
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.
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
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}.
726 (define-ffi-type mytype unsigned-long)
730 Once a type is defined that way, it can be used as if it was a
736 (ffi-size-of-type 'mytype)
741 As mentioned above, we look at the construction of arrays now.
744 (define-ffi-type myarray (array unsigned-long 8))
746 (ffi-size-of-type 'myarray)
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
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}}.
761 @defvr Macro define-ffi-struct name &rest slots
762 Define a new structure of NAME and SLOTS.
766 (define-ffi-struct foo (sl1 unsigned-int) (sl2 char) (sl3 int))
767 @result{} (lambda (obj) "
768 Common Lisp lambda list:
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)
787 @subsection Enumerations
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.
795 For convenience the SXEmacs FFI interface provides a similar
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.
802 @var{specs} can be an arbitrary number of symbols which will be
803 enumerated in the respective order.
805 Additionally the cells of @var{specs} may look like
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}).
812 Moreover, it is possible to set the counter explicitly:
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.
819 The defined enumeration will result in a (@code{defconst}'d) variable
820 @code{name}, the value is an alist of the form
822 @samp{ ((symbol . value) ...)},
824 where @samp{value} is the C-value of @samp{symbol}.
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
839 @section FFI-bindings for libcurl
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.
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.
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
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.
863 @subsection Low-level functions of @file{ffi-curl.el}
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}.
869 @defun curl:easy-init
870 Initialise curl easy interface and return a context handle.
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.
879 Remember to always free all requested context handles. The garbage
880 collector of SXEmacs has no influence on them nor on their allocated
884 (let ((context (curl:easy-init)))
885 (curl:easy-cleanup context))
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.
894 @defun curl:easy-setopt ctx &rest options
895 Set @var{options} for curl transfer in session @var{ctx}.
897 Options are passed as keyword-value-pairs. Supported keywords are:
900 @code{:url} @samp{string} --
901 a valid Uniform Resource Locator.
903 @code{:fstream} @samp{ffi-fo} --
904 a file descriptor to which output is redirected.
909 @defun curl:easy-perform ctx
910 Perform cURL operation on the context @var{ctx}.
912 To control the behaviour of the session or set options into the
913 context, see @code{curl:easy-setopt}.
916 @defun curl:easy-getinfo ctx what
917 Get info from the context @var{ctx} about @var{what}.
920 @defvr Constant curl:errors-alist
921 Alist of error codes and associated clear-text error messages.
925 @subsection User-level functions of @file{ffi-curl.el}
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
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.
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}.
941 (curl:download "http://www.sxemacs.org"
942 (expand-file-name (make-temp-name "curl") (temp-directory)))
949 @section FFI-bindings for libWand
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.
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.
962 @subsection Low-level functions of @file{ffi-wand.el}
964 @c @defvr FFI-type MagickWand
967 @c An alias for '(pointer void).
970 @c @defvr FFI-type MagickBooleanType
971 @c A boolean type for function return values.
973 @c An alias for 'long.
976 @c @defvr FFI-type MagickStorageType
977 @c Type for the enumeration of storage methods.
979 @c An alias for 'unsigned-long.
982 @c @defvr FFI-type MagickChannelType
983 @c Type for the enumeration of channels.
985 @c An alias for 'unsigned-long.
989 Let us begin with context handlers.
991 @defun Wand:make-wand
992 Return a newly allocated MagickWand (the context handle of libWand).
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}.
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}.
1007 @defun Wand:delete-wand wand
1008 Delete the @var{wand}.
1009 This frees all resources associated with the @var{wand}.
1011 WARNING: Do not use @var{wand} after calling this function!
1014 @defun Wand:wandp wand
1015 Return non-@code{nil} if @var{wand} is a magick wand, @code{nil}
1020 (setq foo (Wand:make-wand))
1021 @result{} #<ffiobject type=MagickWand size=4 fotype=0 foptr=0x8b38350>
1024 (Wand:delete-wand foo)
1031 @subsection Input/Output functions of Wand context handles
1034 Now here is an assortment of functions which operate on a Wand.
1037 @defun Wand:read-image wand file
1038 Read @var{file} and associate it with @var{wand}.
1041 @defun Wand:write-image wand file
1042 Write the image associated with @var{wand} to @var{file}.
1045 @defun Wand:display-image wand
1046 Display the image associated with @var{wand}.
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).
1053 @defun Wand:get-image-pixels wand
1054 Return a raw string of image pixel data (RGB triples).
1058 @subsection Image geometry and canvas functions
1060 @c geometry and canvas
1061 @defun Wand:get-image-height wand
1062 Return the height of the image in @var{wand} in pixels.
1064 @defun Wand:get-image-width wand
1065 Return the width of the image in @var{wand} in pixels.
1068 @defun Wand:scale-image wand width height
1069 Scale the image in @var{wand} to the dimensions @var{width} times
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
1079 @defun Wand:flip-image wand
1080 Mirror the image associated with @var{wand} around the x-axis.
1082 @defun Wand:flop-image wand
1083 Mirror the image associated with @var{wand} around the y-axis.
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}.
1092 @subsection Image refinement functions
1094 @c image improvements
1095 @defun Wand:increase-contrast-image wand
1096 Increase the contrast of the image associated with @var{wand}.
1098 @defun Wand:decrease-contrast-image wand
1099 Decrease the contrast of the image associated with @var{wand}.
1102 @defun Wand:despeckle-image wand
1103 Reduce the speckle noise in the image associated with @var{wand}.
1106 @defun Wand:enhance-image wand
1107 Enhance the image associated with @var{wand}.
1110 @defun Wand:equalize-image wand
1111 Equalise the image associated with @var{wand}.
1114 @defun Wand:normalize-image wand
1115 Normalise the image associated with @var{wand}.
1118 @defun Wand:reduce-noise-image wand radius
1119 Reduce the noise in the image associated with @var{wand}.
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.
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.
1136 @defun Wand:median-filter-image wand radius
1137 Perform median normalisation of the pixels in the image associated
1141 @defun Wand:solarize-image wand threshold
1142 Solarise the image associated with @var{wand}.
1145 @defun Wand:modulate-image wand brightness saturation hue
1146 Tweak the image associated with @var{wand}.
1149 @defun Wand:negate-image wand &optional greyp
1150 Perform negation on the image associated with @var{wand}.
1154 @subsection Image effects functions
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.
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.
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.
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.
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
1183 The @var{wavelength} argument is a float and defines how often the
1188 @subsection Image blurring and sharpening functions
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.
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.
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.
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.
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.
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
1231 @subsection User-level functions of @file{ffi-wand.el}
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.
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.
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.
1250 @c ffi.texi ends here