1 ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
3 ;;; mapping.lisp --- An example for mapping Lisp objects to ints.
5 ;;; Copyright (C) 2007, Luis Oliveira <loliveira@common-lisp.net>
7 ;;; Permission is hereby granted, free of charge, to any person
8 ;;; obtaining a copy of this software and associated documentation
9 ;;; files (the "Software"), to deal in the Software without
10 ;;; restriction, including without limitation the rights to use, copy,
11 ;;; modify, merge, publish, distribute, sublicense, and/or sell copies
12 ;;; of the Software, and to permit persons to whom the Software is
13 ;;; furnished to do so, subject to the following conditions:
15 ;;; The above copyright notice and this permission notice shall be
16 ;;; included in all copies or substantial portions of the Software.
18 ;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19 ;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20 ;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21 ;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
22 ;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
23 ;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 ;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25 ;;; DEALINGS IN THE SOFTWARE.
28 ;;; This is an example on how to tackle the problem of passing Lisp
29 ;;; object identifiers to foreign code. It is not a great example,
30 ;;; but might be useful nevertheless.
32 ;;; Requires trivial-garbage: <http://cliki.net/trivial-garbage>
34 (defpackage #:cffi-mapping-test
35 (:use
#:common-lisp
#:cffi
#:trivial-garbage
)
38 (in-package #:cffi-mapping-test
)
40 (define-foreign-type lisp-object-type
()
41 ((weakp :initarg
:weakp
))
42 (:actual-type
:unsigned-int
))
44 (define-parse-method lisp-object
(&key weak-mapping
)
45 (make-instance 'lisp-object-type
:weakp weak-mapping
))
47 (defvar *regular-hashtable
* (make-hash-table))
48 (defvar *weak-hashtable
* (make-weak-hash-table :weakness
:value
))
49 (defvar *regular-counter
* 0)
50 (defvar *weak-counter
* 0)
52 (defun increment-counter (value)
53 (mod (1+ value
) (expt 2 (* 8 (foreign-type-size :unsigned-int
)))))
55 (define-modify-macro incf-counter
() increment-counter
)
57 (defmethod translate-to-foreign (value (type lisp-object-type
))
58 (with-slots (weakp) type
60 (incf-counter *weak-counter
*)
61 (incf-counter *regular-counter
*)))
62 (ht (if weakp
*weak-hashtable
* *regular-hashtable
*)))
63 (setf (gethash id ht
) value
)
66 (defmethod translate-from-foreign (int (type lisp-object-type
))
67 (with-slots (weakp) type
68 (gethash int
(if weakp
*weak-hashtable
* *regular-hashtable
*))))
72 (defctype weak-mapping
(lisp-object :weak-mapping t
))
74 ;;; (run) => #<FUNCTION (LAMBDA (X)) {11AB46F5}>
76 (foreign-funcall "abs" weak-mapping
(lambda (x) x
) weak-mapping
))