ffi_uffi.txi 31.4 KB
Newer Older
1 2
@node UFFI Reference
@subsection UFFI Reference
3
@cindex Universal foreign function interface
4 5

@menu
6 7 8 9 10
* Primitive Types::
* Aggregate Types::
* Foreign Objects::
* Foreign Strings::
* Functions and Libraries::
11
@end menu
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37

@node Primitive Types
@subsubsection Primitive Types
@cindex Foreign primitive types

Primitive types have a single value, these include characters, numbers,
and pointers. They are all symbols in the keyword package.

@lspindex :char
@lspindex :unsigned-char
@lspindex :byte
@lspindex :unsigned-byte
@lspindex :short
@lspindex :unsigned-short
@lspindex :int
@lspindex :unsigned-int
@lspindex :long
@lspindex :unsigned-long
@lspindex :int16_t
@lspindex :uint16_t
@lspindex :int32_t
@lspindex :uint32_t
@lspindex :int64_t
@lspindex :uint64_t
@lspindex :float
@lspindex :double
38
@lspindex :long-double
39 40 41 42
@lspindex :cstring
@lspindex :void
@lspindex :pointer-void
@lspindex :*
43
@lspindex :object
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75

@ftindex LONG-LONG
@ftindex UINT16-T
@ftindex UINT32-T
@ftindex UINT64-T
@ftindex LONG-FLOAT

@table @samp
@item :char
@itemx :unsigned-char
Signed/unsigned 8-bits. Dereferenced pointer returns a character.
@item :byte
@itemx :unsigned-byte
Signed/unsigned 8-bits. Dereferenced pointer returns an integer.
@item  :short
@itemx :unsigned-short
@itemx :int
@itemx :unsigned-int
@itemx :long
@itemx :unsigned-long
Standard integer types (16-bit, 32-bit and 32/64-bit).
@item  :int16_t
@itemx :uint16_t
@itemx :int32_t
@itemx :uint32_t
@itemx :int64_t
@itemx :uint64_t
Integer types with guaranteed bitness.

@item :float
@itemx :double
Floating point numerals (32-bit and 64-bit).
76 77
@item :long-double
Floating point numeral (usually 80-bit, at least 64-bit, exact
78
bitness is compiler/architecture/platform dependent).
79 80 81 82 83 84 85 86 87 88
@item :cstring
A @code{NULL} terminated string used for passing and returning
characters strings with a C function.
@item :void
The absence of a value. Used to indicate that a function does not return
a value.
@item :pointer-void
Points to a generic object.
@item *
Used to declare a pointer to an object.
89 90
@item :object
A generic lisp object (i.e. a @code{cl_object} in C)
91 92
@end table

93
@subsubheading Reference
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123

@lspindex ffi:def-constant
@defmac ffi:def-constant name value &key (export nil)

Binds a symbol to a constant.

@table @var
@item name
A symbol that will be bound to the value.
@item value
An evaluated form that is bound the the name.
@item export
When @code{T}, the name is exported from the current package. Defaults
to @code{NIL}.
@item returns
Constant name.
@end table

@subsubheading Description
This is a thin wrapper around @code{defconstant}. It evaluates at
compile-time and optionally exports the symbol from the package.

@subsubheading Examples
@exindex @code{ffi:def-constant} defining constants
@lisp
(ffi:def-constant pi2 (* 2 pi))
(ffi:def-constant exported-pi2 (* 2 pi) :export t)
@end lisp

@subsubheading Side Effects
124
Creates a new special variable.
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
@end defmac



@lspindex ffi:def-foreign-type
@defmac ffi:def-foreign-type name definition

Defines a new foreign type

@table @var
@item name
A symbol naming the new foreign type.
@item value
A form that is not evaluated that defines the new foreign type.
@item returns
Foreign type designator (@var{value}).
@end table

@subsubheading Description
Defines a new foreign type

@subsubheading Examples
@exindex @code{ffi:def-foreign-type} examples
@lisp
149 150 151
(ffi:def-foreign-type my-generic-pointer :pointer-void)
(ffi:def-foreign-type a-double-float :double-float)
(ffi:def-foreign-type char-ptr (* :char))
152 153 154 155 156 157 158 159 160
@end lisp

@subsubheading Side effects
Defines a new foreign type.
@end defmac



@lspindex ffi:null-char-p
161
@defun ffi:null-char-p char
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185

Tests a character for NULL value

@table @var
@item char
A character or integer.
@item returns
A boolean flag indicating if @var{char} is a NULL value.
@end table

@subsubheading Description
A predicate testing if a character or integer is NULL. This abstracts
the difference in implementations where some return a character and some
return a integer whence dereferencing a C character pointer.

@subsubheading Examples
@exindex @code{ffi:null-char-p} example
@lisp
(ffi:def-array-pointer ca :unsigned-char)
  (let ((fs (ffi:convert-to-foreign-string "ab")))
    (values (ffi:null-char-p (ffi:deref-array fs 'ca 0))
            (ffi:null-char-p (ffi:deref-array fs 'ca 2))))
;; => NIL T
@end lisp
186
@end defun
187 188 189 190 191 192 193 194 195 196



@node Aggregate Types
@subsubsection Aggregate Types
@cindex Foreign aggregate types

@subsubheading Overview
Aggregate types are comprised of one or more primitive types.

197 198
@subsubheading Reference

199
@lspindex ffi:def-enum
200
@defmac ffi:def-enum name fields &key separator-string
201 202 203 204 205 206 207

Defines a C enumeration

@table @var
@item name
A symbol that names the enumeration.
@item fields
208
A list of field definitions. Each definition can be a symbol or a list of
209 210 211 212 213 214 215 216 217 218 219 220 221 222
two elements. Symbols get assigned a value of the current counter which
starts at 0 and increments by 1 for each subsequent symbol. It the field
definition is a list, the first position is the symbol and the second
position is the value to assign the the symbol. The current counter gets
set to 1+ this value.
@item returns
A string that governs the creation of constants. The default is "#".
@end table

@subsubheading Description
Declares a C enumeration. It generates constants with integer values for
the elements of the enumeration. The symbols for the these constant
values are created by the concatenation of the enumeration name,
separator-string, and field symbol. Also creates a foreign type with the
223
name name of type @code{:int}.
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250

@subsubheading Examples
@exindex @code{ffi:def-enum} sample enumerations
@lisp
(ffi:def-enum abc (:a :b :c)) 
;; Creates constants abc#a (1), abc#b (2), abc#c (3) and defines
;; the foreign type "abc" to be :int

(ffi:def-enum efoo (:e1 (:e2 10) :e3) :separator-string "-")
;; Creates constants efoo-e1 (1), efoo-e2 (10), efoo-e3 (11) and defines
;; the foreign type efoo to be :int
@end lisp

@subsubheading Side effects
Creates a @code{:int} foreign type, defines constants.
@end defmac



@defmac ffi:def-struct name &rest fields

Defines a C structure

@table @var
@item name
A symbol that names the structure. 
@item fields
251
A variable number of field definitions. Each definition is a list
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
consisting of a symbol naming the field followed by its foreign type.
@end table

@subsubheading Description
Declares a structure. A special type is available as a slot in the
field. It is a pointer that points to an instance of the parent
structure. It's type is @code{:pointer-self}.

@subsubheading Examples
@exindex @code{ffi:def-struct} defining C structure
@lisp
(ffi:def-struct foo (a :unsigned-int) 
  (b    (* :char)) 
  (c    (:array :int 10)) 
  (next :pointer-self))
@end lisp

@subsubheading Side effects
Creates a foreign type.
@end defmac



@lspindex ffi:get-slot-value
276
@defun ffi:get-slot-value obj type field
277 278 279 280 281

Retrieves a value from a slot of a structure

@table @var
@item obj
282
A pointer to the foreign structure.
283
@item type
284
The name of the foreign structure.
285
@item field
286
The name of the desired field in the foreign structure.
287 288 289 290 291 292
@item returns
The value of the @code{field} in the structure @code{obj}.
@end table

@subsubheading Description
Accesses a slot value from a structure. This is generalized and can be
293
used with @code{setf}.
294 295

@subsubheading Examples
296
@exindex @code{ffi:get-slot-value} manipulating a struct field
297
@lisp
298 299
(ffi:get-slot-value foo-ptr 'foo-structure 'field-name)
(setf (ffi:get-slot-value foo-ptr 'foo-structure 'field-name) 10)
300
@end lisp
301 302 303 304 305 306 307 308 309 310 311 312 313
@end defun



@lspindex ffi:get-slot-pointer
@defun ffi:get-slot-pointer obj type field

Retrieves a pointer from a slot of a structure

@table @var
@item obj
A pointer to the foreign structure.
@item type
314
The name of the foreign structure.
315
@item field
316
The name of the desired field in the foreign structure.
317 318 319 320 321
@item returns
The value of the pointer @var{field} in the structure @var{obj}.
@end table

@subsubheading Description
322 323
This is similar to @code{get-slot-value}. It is used when the value of
a slot is a pointer type.
324 325 326 327

@subsubheading Examples
@exindex @code{ffi:get-slot-value} usage
@lisp
328
(ffi:get-slot-pointer foo-ptr 'foo-structure 'my-char-ptr)
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
@end lisp
@end defun



@lspindex ffi:def-array-pointer
@defmac ffi:def-array-pointer name type

Defines a pointer to an array of @var{type}

@table @var
@item name
A name of the new foreign type. 
@item type
The foreign type of the array elements.
@end table

@subsubheading Description
Defines a type that is a pointer to an array of @var{type}.

@subsubheading Examples
@exindex @code{ffi:def-array-pointer} usage
@lisp
352
(ffi:def-array-pointer byte-array-pointer :unsigned-char)
353 354 355 356 357 358 359 360 361 362 363
@end lisp

@subsubheading Side effects
Defines a new foreign type.
@end defmac



@lspindex ffi:deref-array
@defun ffi:deref-array array type position

364
Dereference an array
365 366 367 368 369 370 371 372 373 374 375 376 377 378

@table @var
@item array
A foreign array.
@item type
The foreign type of the @var{array}.
@item position
An integer specifying the position to retrieve from the @var{array}.
@item returns
The value stored in the @var{position} of the @var{array}.
@end table

@subsubheading Description
Dereferences (retrieves) the value of the foreign array
379
element. @code{setf}-able.
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402

@subsubheading Examples
@exindex @code{ffi:deref-array} retrieving array element
(ffi:def-array-pointer ca :char)
  (let ((fs (ffi:convert-to-foreign-string "ab")))
    (values (ffi:null-char-p (ffi:deref-array fs 'ca 0))
    (ffi:null-char-p (ffi:deref-array fs 'ca 2))))
;; => NIL T
@lisp
@end lisp
@end defun



@lspindex ffi:def-union
@defmac ffi:def-union name &rest fields

Defines a foreign union type

@table @var
@item name
A name of the new union type.
@item fields
403
A list of fields of the union in form @code{(field-name field-type)}.
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
@end table

@subsubheading Description
Defines a foreign union type. 

@subsubheading Examples
@exindex @code{ffi:def-union} union definition and usage
@lisp
(ffi:def-union test-union
  (a-char :char)
  (an-int :int))

(let ((u (ffi:allocate-foreign-object 'test-union)))
  (setf (ffi:get-slot-value u 'test-union 'an-int) (+ 65 (* 66 256)))
  (prog1
     (ffi:ensure-char-character (ffi:get-slot-value u 'test-union 'a-char))
   (ffi:free-foreign-object u)))
;; => #\A
@end lisp

@subsubheading Side effects
Defines a new foreign type.
@end defmac

428 429
@node Foreign Objects
@subsubsection Foreign Objects
430 431 432 433 434 435
@cindex Foreign objects

@subsubheading Overview
Objects are entities that can allocated, referred to by pointers, and
can be freed.

436
@subsubheading Reference
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559

@lspindex ffi:allocate-foreign-object
@defun ffi:allocate-foreign-object type &optional size

Allocates an instance of a foreign object

@table @var
@item type
The type of foreign object to allocate. This parameter is evaluated.
@item size
An optional size parameter that is evaluated. If specified, allocates
and returns an array of @var{type} that is @var{size} members long. This
parameter is evaluated.
@item returns
A pointer to the foreign object.
@end table

@subsubheading Description
Allocates an instance of a foreign object. It returns a pointer to the
object.

@subsubheading Examples
@exindex @code{ffi:allocate-foreign-object} allocating structure object
@lisp
(ffi:def-struct ab (a :int) (b :double))
;; => (:STRUCT (A :INT) (B :DOUBLE))
(ffi:allocate-foreign-object 'ab)
;; => #<foreign AB>
@end lisp
@end defun

@lspindex ffi:free-foreign-object
@defun ffi:free-foreign-object ptr

Frees memory that was allocated for a foreign object

@table @var
@item ptr
A pointer to the allocated foreign object to free.
@end table

@subsubheading Description
Frees memory that was allocated for a foreign object.
@end defun

@lspindex ffi:with-foreign-object
@defmac ffi:with-foreign-object (var type) &body body

Wraps the allocation, binding and destruction of a foreign object around
a body of code

@table @var
@item var
Variable name to bind.
@item type
Type of foreign object to allocate. This parameter is evaluated.
@item body
Code to be evaluated.
@item returns
The result of evaluating the body.
@end table

@subsubheading Description
This function wraps the allocation, binding, and destruction of a
foreign object around the body of code.

@subsubheading Examples
@exindex @code{ffi:with-foreign-object} macro usage
@lisp
(defun gethostname2 ()
  "Returns the hostname"
  (ffi:with-foreign-object (name '(:array :unsigned-char 256))
    (if (zerop (c-gethostname (ffi:char-array-to-pointer name) 256))
        (ffi:convert-from-foreign-string name)
        (error "gethostname() failed."))))
@end lisp
@end defmac

@lspindex ffi:size-of-foreign-type
@defmac ffi:size-of-foreign-type ftype

Returns the number of data bytes used by a foreign object type

@table @var
@item ftype
A foreign type specifier. This parameter is evaluated.
@item returns
Number of data bytes used by a foreign object @var{ftype}.
@end table

@subsubheading Description
Returns the number of data bytes used by a foreign object type. This
does not include any Lisp storage overhead.

@subsubheading Examples
@exindex @code{ffi:size-of-foreign-type}
@lisp
(ffi:size-of-foreign-type :unsigned-byte)
;; => 1
(ffi:size-of-foreign-type 'my-100-byte-vector-type)
;; => 100
@end lisp
@end defmac

@lspindex ffi:pointer-address
@defun ffi:pointer-address ptr

Returns the address of a pointer

@table @var
@item ptr
A pointer to a foreign object.
@item returns
An integer representing the pointer's address.
@end table

@subsubheading Description
Returns the address as an integer of a pointer.
@end defun

@lspindex ffi:deref-pointer
@defun ffi:deref-pointer ptr ftype

560
Dereferences a pointer
561 562 563 564 565 566 567 568 569 570 571

@table @var
@item ptr
Pointer to a foreign object.
@item ftype
Foreign type of the object being pointed to.
@item returns
The value of the object where the pointer points.
@end table

@subsubheading Description
572
Returns the object to which a pointer points. @code{setf}-able.
573 574

@subsubheading Notes
575 576
Casting of the pointer may be performed with @code{with-cast-pointer}
together with the @code{deref-pointer}/@code{deref-array}.
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603

@subsubheading Examples
@exindex @code{ffi:deref-pointer}
@lisp
(let ((intp (ffi:allocate-foreign-object :int)))
  (setf (ffi:deref-pointer intp :int) 10)
  (prog1
      (ffi:deref-pointer intp :int)
    (ffi:free-foreign-object intp)))
;; => 10
@end lisp
@end defun

@lspindex ffi:ensure-char-character
@defun ffi:ensure-char-character object

Ensures that a dereferenced @code{:char} pointer is a character

@table @var
@item object
Either a character or a integer specifying a character code.
@item returns
A character.
@end table

@subsubheading Description
Ensures that an objects obtained by dereferencing @code{:char} and
604
@code{:unsigned-char} pointers is a lisp character.
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678

@subsubheading Examples
@exindex @code{ffi:ensure-char-character}
@lisp
(let ((fs (ffi:convert-to-foreign-string "a")))
  (prog1 
      (ffi:ensure-char-character (ffi:deref-pointer fs :char))
    (ffi:free-foreign-object fs)))
;; => #\a
@end lisp

@subsubheading Exceptional Situations
Depending upon the implementation and what UFFI expects, this macro may
signal an error if the object is not a character or integer.
@end defun

@lspindex ffi:ensure-char-integer
@defun ffi:ensure-char-integer object

Ensures that a dereferenced @code{:char} pointer is an integer

@table @var
@item object
Either a character or a integer specifying a character code.
@item returns
An integer.
@end table

@subsubheading Description
Ensures that an objects obtained by dereferencing @code{:char} and
@code{:unsigned-char} pointers is a lisp integer.

@subsubheading Examples
@exindex @code{ffi:ensure-char-integer}
@lisp
(let ((fs (ffi:convert-to-foreign-string "a")))
  (prog1 
      (ffi:ensure-char-integer (ffi:deref-pointer fs :char))
    (ffi:free-foreign-object fs)))
;; => 96
@end lisp

@subsubheading Exceptional Situations
Depending upon the implementation and what UFFI expects, this macro may
signal an error if the object is not a character or integer.
@end defun

@lspindex ffi:make-null-pointer
@defun ffi:make-null-pointer ftype

Create a NULL pointer of a specified type

@table @var
@item ftype
A type of object to which the pointer refers.
@item returns
The NULL pointer of type @var{ftype}.
@end table
@end defun

@lspindex ffi:null-pointer-p
@defun ffi:null-pointer-p ptr

Tests a pointer for NULL value

@table @var
@item ptr
A foreign object pointer.
@item returns
The boolean flag.
@end table
@end defun

@lspindex ffi:+null-cstring-pointer+
679
@defvr Variable {ffi:+null-cstring-pointer+}
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
A NULL cstring pointer. This can be used for testing if a cstring
returned by a function is NULL.
@end defvr

@lspindex ffi:with-cast-pointer
@defmac ffi:with-cast-pointer (var ptr ftype) &body body

Wraps a body of code with a pointer cast to a new type

@table @var
@item var
Symbol which will be bound to the casted object.
@item ptr
Pointer to a foreign object.
@item ftype
A foreign type of the object being pointed to.
@item returns
The value of the object where the pointer points.
@end table

@subsubheading Description
701 702 703
Executes @var{body} with @var{ptr} cast to be a pointer to type
@var{ftype}. @var{var} will be bound to this value during the
execution of @var{body}.
704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727

@subsubheading Examples
@exindex @code{ffi:with-cast-pointer}
@lisp
(ffi:with-foreign-object (size :int)
  ;; FOO is a foreign function returning a :POINTER-VOID
  (let ((memory (foo size)))
    (when (mumble)
      ;; at this point we know for some reason that MEMORY points
      ;; to an array of unsigned bytes
      (ffi:with-cast-pointer (memory :unsigned-byte)
        (dotimes (i (deref-pointer size :int))
          (do-something-with
              (ffi:deref-array memory '(:array :unsigned-byte) i)))))))
@end lisp
@end defmac

@lspindex ffi:def-foreign-var
@defmac ffi:def-foreign-var name type module

Defines a symbol macro to access a variable in foreign code

@table @var
@item name
728
A string or list specifying the symbol macro's name. If it is a
729
string, that names the foreign variable. A Lisp name is created by
730
translating @code{#\_} to @code{#\-} and by converting to upper-case.
731 732 733 734 735 736

If it is a list, the first item is a string specifying the foreign
variable name and the second it is a symbol stating the Lisp name.
@item type
A foreign type of the foreign variable.
@item module
737 738 739
Either a string specifying the module (or library) the foreign
variable resides in, @code{:default} if no module needs to be loaded
or @code{NIL} to use SFFI.
740 741 742 743 744 745 746
@end table

@subsubheading Description
Defines a symbol macro which can be used to access (get and set) the
value of a variable in foreign code.

@subsubheading Examples
747
@exindex @code{ffi:def-foreign-var} places in foreign world
748

749
C code defining foreign structure, standalone integer and the accessor:
750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766
@example
@verbatim
int baz = 3;

typedef struct {
  int x;
  double y;
} foo_struct;

foo_struct the_struct = { 42, 3.2 };

int foo () {
  return baz;
}
@end verbatim
@end example

767
Lisp code defining C structure, function and a variable:
768
@lisp
769 770
(ffi:def-struct foo-struct
  (x :int)
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
  (y :double))

(ffi:def-function ("foo" foo) ()
  :returning :int
  :module "foo")

(ffi:def-foreign-var ("baz" *baz*) :int "foo")
(ffi:def-foreign-var ("the_struct" *the-struct*) foo-struct "foo")

*baz*           ;; => 3
(incf *baz*)    ;; => 4
(foo)           ;; => 4
@end lisp
@end defmac

786 787 788
@node Foreign Strings
@subsubsection Foreign Strings
@cindex Foreign strings
789

790
@subsubheading Overview
791
@cindex cstring and foreign string differences
792

793 794 795 796 797 798
UFFI has functions to two types of C-compatible strings: cstrings and
foreign strings. cstrings are used only as parameters to and from
functions. In some implementations a cstring is not a foreign type but
rather the Lisp string itself. On other platforms a cstring is a newly
allocated foreign vector for storing characters. The following is an
example of using cstrings to both send and return a value.
799

800
@exindex cstring used to send and return a value
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
@lisp
(ffi:def-function ("getenv" c-getenv) 
    ((name :cstring))
  :returning :cstring)

(defun my-getenv (key)
  "Returns an environment variable, or NIL if it does not exist"
  (check-type key string)
  (ffi:with-cstring (key-native key)
    (ffi:convert-from-cstring (c-getenv key-native))))
@end lisp

In contrast, foreign strings are always a foreign vector of characters
which have memory allocated. Thus, if you need to allocate memory to
hold the return value of a string, you must use a foreign string and not
a cstring. The following is an example of using a foreign string for a
return value.

819
@exindex foreign string used to send and return a value
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
@lisp
(ffi:def-function ("gethostname" c-gethostname)
    ((name (* :unsigned-char))
     (len :int))
  :returning :int)

(defun gethostname ()
  "Returns the hostname"
  (let* ((name (ffi:allocate-foreign-string 256))
         (result-code (c-gethostname name 256))
         (hostname (when (zerop result-code)
                     (ffi:convert-from-foreign-string name))))
    ;; UFFI does not yet provide a universal way to free
    ;; memory allocated by C's malloc. At this point, a program
    ;; needs to call C's free function to free such memory.
    (unless (zerop result-code)
      (error "gethostname() failed."))))
@end lisp

Foreign functions that return pointers to freshly allocated strings
840 841 842
should in general not return cstrings, but foreign strings. (There is
no portable way to release such cstrings from Lisp.) The following is
an example of handling such a function.
843

844
@exindex Conversion between foreign string and cstring
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
@lisp
(ffi:def-function ("readline" c-readline)
    ((prompt :cstring))
  :returning (* :char))

(defun readline (prompt)
  "Reads a string from console with line-editing."
  (ffi:with-cstring (c-prompt prompt)
    (let* ((c-str (c-readline c-prompt))
           (str (ffi:convert-from-foreign-string c-str)))
      (ffi:free-foreign-object c-str)
      str)))
@end lisp

@subsubheading Reference

@lspindex ffi:convert-from-cstring
@defmac ffi:convert-from-cstring object
Converts a @code{cstring} to a Lisp string
@table @var
@item object
866
A @code{cstring}
867
@item returns
868
A Lisp string
869 870 871 872 873 874 875 876 877 878
@end table

@subsubheading Description
Converts a Lisp string to a cstring. This is most often used when
processing the results of a foreign function that returns a cstring.
@end defmac

@lspindex ffi:convert-to-cstring
@defmac ffi:convert-to-cstring object
Converts a Lisp string to a @code{cstring}
879
@table @var
880
@item object
881
A Lisp string
882
@item returns
883
A @code{cstring}
884 885 886
@end table

@subsubheading Description
887 888
Converts a Lisp string to a @code{cstring}. The @code{cstring} should
be freed with @code{free-cstring}.
889 890 891 892
@subsubheading Side Effects
This function allocates memory.
@end defmac

893

894 895 896 897 898 899 900 901
@lspindex ffi:free-cstring
@defmac ffi:convert-from-cstring cstring
Free memory used by @var{cstring}
@table @var
@item cstring
@code{cstring} to be freed.
@end table
@subsubheading Description
902 903
Frees any memory possibly allocated by @code{convert-to-cstring}. On ECL, a
@code{cstring} is just the Lisp string itself.
904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922
@end defmac


@lspindex ffi:with-cstring
@defmac ffi:with-cstring (cstring string) &body body
Binds a newly created @code{cstring}
@table @var
@item cstring
A symbol naming the @code{cstring} to be created.
@item string
A Lisp string that will be translated to a @code{cstring}.
@item body
The body of where the @var{cstring} will be bound.
@item returns
Result of evaluating the @var{body}.
@end table
@subsubheading Description
Binds a symbol to a @code{cstring} created from conversion of a
@var{string}. Automatically frees the @var{cstring}.
923
@subsubheading Examples
924
@exindex @code{with-cstring}
925
@lisp
926 927 928 929 930 931 932 933 934
(ffi:def-function ("getenv" c-getenv) 
    ((name :cstring))
  :returning :cstring)

(defun getenv (key)
  "Returns an environment variable, or NIL if it does not exist"
  (check-type key string)
  (ffi:with-cstring (key-cstring key)
    (ffi:convert-from-cstring (c-getenv key-cstring))))
935 936 937
@end lisp
@end defmac

938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
@lspindex ffi:with-cstrings
@defmac ffi:with-cstrings bindings &body body
Binds a newly created @code{cstrings}
@table @var
@item bindings
List of pairs @var{(cstring string)}, where @var{cstring} is a name
for a @code{cstring} translated from Lisp string @var{string}.
@item body
The body of where the @var{bindings} will be bound.
@item returns
Result of evaluating the @var{body}.
@end table
@subsubheading Description
Binds a symbols to a @code{cstring}s created from conversion of a
@var{string}s. Automatically frees the @var{cstring}s. This macro works
953
similar to @code{let*}. Based on @code{with-cstring}.
954
@end defmac
955

956 957 958 959 960 961 962 963 964 965
@lspindex ffi:convert-from-foreign-string
@defmac ffi:convert-from-foreign-string foreign-string &key length (null-terminated-p t)
Converts a foreign string into a Lisp string
@table @var
@item foreign-string
A foreign string.
@item length
The length of the foreign string to convert. The default is the length
of the string until a NULL character is reached.
@item null-terminated-p
966
A boolean flag with a default value of @code{T}. When true, the string is
967 968 969 970 971
converted until the first NULL character is reached.
@item returns
A Lisp string.
@end table
@subsubheading Description
972
Returns a Lisp string from a foreign string. Can translate ASCII and
973 974
binary strings.
@end defmac
975

976
@lspindex ffi:convert-to-foreign-string
977
@defmac ffi:convert-to-foreign-string string
978
Converts a Lisp string to a foreign string
979
@table @var
980 981
@item string
A Lisp string.
982
@item returns
983
A foreign string.
984
@end table
985 986
@subsubheading Description
Converts a Lisp string to a foreign string. Memory should be freed with
987
@code{free-foreign-object}.
988
@end defmac
989

990 991 992 993 994 995 996
@lspindex ffi:allocate-foreign-string
@defmac ffi:allocate-foreign-string size &key unsigned
Allocates space for a foreign string
@table @var
@item size
The size of the space to be allocated in bytes.
@item unsigned
997 998
A boolean flag with a default value of @code{T}. When true, marks the pointer
as an @code{:unsigned-char}.
999 1000 1001
@item returns
A foreign string which has undefined contents.
@end table
1002
@subsubheading Description
1003
Allocates space for a foreign string. Memory should be freed with
1004
@code{free-foreign-object}.
1005
@end defmac
1006

1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
@lspindex ffi:with-foreign-string
@defmac ffi:with-foreign-string (foreign-string string) &body body
Binds a newly allocated @code{foreign-string}
@table @var
@item foreign-string
A symbol naming the @code{foreign string} to be created.
@item string
A Lisp string that will be translated to a @code{foreign string}.
@item body
The body of where the @var{foreign-string} will be bound.
@item returns
Result of evaluating the @var{body}.
@end table
@subsubheading Description
Binds a symbol to a @code{foreign-string} created from conversion of a
@var{string}. Automatically deallocates the @var{foreign-string}.
1023
@subsubheading Examples
1024
@end defmac
1025

1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
@lspindex ffi:with-foreign-strings
@defmac ffi:with-foreign-strings bindings &body body
Binds a newly created @code{foreign string}
@table @var
@item bindings
List of pairs @var{(foreign-string string)}, where @var{foreign-string}
is a name for a @code{foreign string} translated from Lisp string
@var{string}.
@item body
The body of where the @var{bindings} will be bound.
@item returns
Result of evaluating the @var{body}.
@end table
@subsubheading Description
Binds a symbols to a @code{foreign-string}s created from conversion of a
@var{string}s. Automatically frees the @var{foreign-string}s. This macro
1042
works similar to @code{let*}. Based on @code{with-foreign-string}.
1043
@end defmac
1044 1045 1046 1047 1048

@node Functions and Libraries
@subsubsection Functions and Libraries
@cindex Foreign functions and libraries

1049
@subsubheading Reference
1050

1051 1052 1053 1054
@lspindex ffi:def-function
@defmac ffi:def-function name args &key module (returning :void) (call :cdecl)
@table @var
@item name
1055
A string or list specifying the function name. If it is a string, that
1056 1057 1058 1059 1060 1061 1062 1063 1064
names the foreign function. A Lisp name is created by translating
@code{#\_} to @code{#\-} and by converting to upper-case in
case-insensitive Lisp implementations. If it is a list, the first item
is a string specifying the foreign function name and the second it is a
symbol stating the Lisp name.
@item args
A list of argument declarations. If @code{NIL}, indicates that the function
does not take any arguments.
@item module
1065 1066 1067
Either a string specifying which module (or library) that the foreign
function resides, @code{:default} if no module needs to be loaded or
@code{NIL} to use SFFI.
1068
@item call
1069 1070
Function calling convention. May be one of @code{:default}, @code{:cdecl},
@code{:sysv}, @code{:stdcall}, @code{:win64} and
1071 1072 1073 1074 1075 1076
@code{unix64}.

This argument is used only when we're using the dynamic function
interface. If ECL is built without the DFFI support, then it uses SFFI
the @var{call} argument is ignored.
@item returning
1077 1078
A declaration specifying the result type of the foreign function.
@code{:void} indicates that the function does not return any value.
1079 1080 1081 1082 1083 1084
@end table
@subsubheading Description
Declares a foreign function.
@subsubheading Examples
@exindex @code{ffi:def-function}
@lisp
1085
(ffi:def-function "gethostname"
1086 1087
    ((name (* :unsigned-char))
     (len :int))
1088
  :returning :int)
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
@end lisp
@end defmac

@lspindex ffi:load-foreign-library
@defmac ffi:load-foreign-library filename &key module supporting-libraries force-load system-library
@table @var
@item filename
A string or pathname specifying the library location in the filesystem.
@item module
@strong{IGNORED} A string designating the name of the module to apply to
functions in this library.
@item supporting-libraries
@strong{IGNORED} A list of strings naming the libraries required to link
the foreign library.
@item force-load
@strong{IGNORED} Forces the loading of the library if it has been
previously loaded.
@item system-library
Denotes if the loaded library is a system library (accessible with the
correct linker flags). If @code{T}, then SFFI is used and the linking is
performed after compilation of the module. Otherwise (default) both SFFI
and DFFI are used, but SFFI only during the compilation.
@item returns
A generalized boolean @emph{true} if the library was able to be loaded
successfully or if the library has been previously loaded, otherwise
1114
@code{NIL}.
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
@end table
@subsubheading Description
Loads a foreign library. Ensures that a library is only loaded once
during a session.
@subsubheading Examples
@exindex @code{ffi:load-foreign-library}
@lisp
(ffi:load-foreign-library #p"/usr/lib/libmagic.so.1")
;; => #<codeblock "/usr/lib/libmagic.so">
@end lisp
@subsubheading Side Effects
Loads the foreign code into the Lisp system.
@subsubheading Affected by
Ability to load the file.
@end defmac

@lspindex ffi:find-foreign-library
@defun ffi:find-foreign-library names directories &key drive-letters types
Finds a foreign library file
@table @var
@item names
A string or list of strings containing the base name of the library
file.
@item directories
A string or list of strings containing the directory the library file.
@item drive-letters
A string or list of strings containing the drive letters for the library
file.
@item types
A string or list of strings containing the file type of the library
1145 1146
file. Default is @code{NIL}. If @code{NIL}, will use a default type
based on the currently running implementation.
1147
@item returns
1148 1149
A path containing the path to the @emph{first} file found, or
@code{NIL} if the library file was not found.
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
@end table
@subsubheading Description
Finds a foreign library by searching through a number of possible
locations. Returns the path of the first found file.
@subsubheading Examples
@exindex @code{ffi:find-foreign-library}
@lisp
(ffi:find-foreign-library '("libz" "libmagic")
                          '("/usr/local/lib/" "/usr/lib/")
                          :types '("so" "dll"))
;; => #P"/usr/lib/libz.so.1.2.8"
@end lisp
@end defun
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189

@c @lspindex ffi:
@c @defmac ffi:

@c desc

@c @table @var
@c @item arg-1
@c description
@c @item arg-2
@c description
@c @item returns
@c One value? More?
@c @end table

@c @subsubheading Description
@c Description here

@c @subsubheading Examples
@c @exindex @code{ffi:} sample run
@c @lisp

@c @end lisp

@c @subsubheading Side effects
@c foo bar
@c @end defmac