chiark / gitweb /
Changes required by SBCL
[clg] / glib / proxy.lisp
index 7831a7677276da190d50ddd4cbd6f8258deef554..6ad8b907363828c28ad0e4cfac74fa2fb02b30dd 100644 (file)
 ;; License along with this library; if not, write to the Free Software
 ;; Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
-;; $Id: proxy.lisp,v 1.7 2002-01-20 14:52:04 espen Exp $
+;; $Id: proxy.lisp,v 1.19 2005-02-03 23:09:04 espen Exp $
 
 (in-package "GLIB")
 
-
 ;;;; Superclass for all metaclasses implementing some sort of virtual slots
 
 (eval-when (:compile-toplevel :load-toplevel :execute)
-  (defclass virtual-slot-class (pcl::standard-class))
+  (defclass virtual-slots-class (standard-class) 
+    ())
 
   (defclass direct-virtual-slot-definition (standard-direct-slot-definition)
     ((setter :reader slot-definition-setter :initarg :setter)
-     (getter :reader slot-definition-getter :initarg :getter)))
+     (getter :reader slot-definition-getter :initarg :getter)
+     (unbound :reader slot-definition-unbound :initarg :unbound)
+     (boundp :reader slot-definition-boundp :initarg :boundp)))
   
-  (defclass effective-virtual-slot-definition
-    (standard-effective-slot-definition)))
+  (defclass effective-virtual-slot-definition (standard-effective-slot-definition)
+    ((setter :reader slot-definition-setter :initarg :setter)
+     (getter :reader slot-definition-getter :initarg :getter)
+     (unbound :reader slot-definition-unbound :initarg :unbound)
+     (boundp :reader slot-definition-boundp :initarg :boundp))))
   
+  (defvar *unbound-marker* (gensym "UNBOUND-MARKER-"))
+
+  (defun most-specific-slot-value (instances slot &optional 
+                                  (default *unbound-marker*))
+    (let ((object (find-if
+                  #'(lambda (ob)
+                      (and (slot-exists-p ob slot) (slot-boundp ob slot)))
+                  instances)))
+      (if object
+         (slot-value object slot)
+         default)));)
 
-(defmethod direct-slot-definition-class ((class virtual-slot-class) initargs)
+  
+
+(defmethod direct-slot-definition-class ((class virtual-slots-class) &rest initargs)
   (if (eq (getf initargs :allocation) :virtual)
       (find-class 'direct-virtual-slot-definition)
     (call-next-method)))
 
-(defmethod effective-slot-definition-class ((class virtual-slot-class) initargs)
+(defmethod effective-slot-definition-class ((class virtual-slots-class) &rest initargs)
   (if (eq (getf initargs :allocation) :virtual)
       (find-class 'effective-virtual-slot-definition)
     (call-next-method)))
 
-(defun %most-specific-slot-value (slotds slot &optional default)
-  (let ((slotd
-        (find-if
-         #'(lambda (slotd)
-             (and
-              (slot-exists-p slotd slot)
-              (slot-boundp slotd slot)))
-         slotds)))
-    (if slotd
-       (slot-value slotd slot)
-      default)))
-(defgeneric compute-virtual-slot-accessors (class slotd direct-slotds))
-
-(defmethod compute-virtual-slot-accessors
-    ((class virtual-slot-class)
-     (slotd effective-virtual-slot-definition)
-     direct-slotds)
-    (let ((getter (%most-specific-slot-value direct-slotds 'getter))
-         (setter (%most-specific-slot-value direct-slotds 'setter)))
-      (list getter setter)))
-
-(defmethod compute-effective-slot-definition
-    ((class virtual-slot-class) direct-slotds)
-  (let ((slotd (call-next-method)))
-    (when (typep slotd 'effective-virtual-slot-definition)
+
+(defmethod initialize-internal-slot-functions ((slotd effective-virtual-slot-definition))
+  (if (not (slot-boundp slotd 'getter))
       (setf
-       (slot-value slotd 'pcl::location)
-       (compute-virtual-slot-accessors class slotd direct-slotds)))
-    slotd))
+       (slot-value slotd 'reader-function)
+       #'(lambda (object)
+          (declare (ignore object))
+          (error "Can't read slot: ~A" (slot-definition-name slotd)))
+       (slot-value slotd 'boundp-function)
+       #'(lambda (object) (declare (ignore object)) nil))
+
+    (let ((getter-function
+          (let ((getter (slot-value slotd 'getter)))
+            (etypecase getter
+              (function getter)
+              (symbol 
+               #'(lambda (object)
+                   (funcall getter object)))
+              (string 
+               (let ((reader nil))
+                 (setf (slot-value slotd 'reader-function)
+                       #'(lambda (object)
+                           (unless reader
+                             (setq reader
+                              (mkbinding getter 
+                               (slot-definition-type slotd) 'pointer)))
+                           (funcall reader (proxy-location object))))))))))
+
+      (setf 
+       (slot-value slotd 'boundp-function)
+       (cond
+       ((slot-boundp slotd 'unbound)
+        (let ((unbound-value (slot-value slotd 'unbound)))
+          #'(lambda (object)
+              (not (eq (funcall getter-function object) unbound-value)))))
+       ((slot-boundp slotd 'boundp)
+        (let ((boundp (slot-value slotd 'boundp)))
+          (etypecase boundp
+            (function boundp)
+            (symbol #'(lambda (object)
+                        (funcall boundp object)))
+            (string (let ((reader ()))
+                      #'(lambda (object)
+                          (unless reader
+                            (setq reader
+                             (mkbinding boundp
+                              (slot-definition-type slotd) 'pointer)))
+                          (funcall reader (proxy-location object))))))))
+       ((multiple-value-bind (unbound-p unbound-value)
+            (unbound-value (slot-definition-type slotd))
+          (when unbound-p
+            #'(lambda (object)
+                (not (eq (funcall getter-function object) unbound-value))))))
+       (#'(lambda (object) (declare (ignore object)) t))))
+
+      (setf
+       (slot-value slotd 'reader-function)
+       (cond
+       ((slot-boundp slotd 'unbound)
+        (let ((unbound (slot-value slotd 'unbound))
+              (slot-name (slot-definition-name slotd)))
+          #'(lambda (object)
+              (let ((value (funcall getter-function object)))
+                (if (eq value unbound)
+                    (slot-unbound (class-of object) object slot-name)
+                  value)))))
+       ((slot-boundp slotd 'boundp)
+        (let ((boundp-function (slot-value slotd 'boundp-function)))
+          #'(lambda (object)
+              (and
+               (funcall boundp-function object)
+               (funcall getter-function object)))))
+       ((multiple-value-bind (unbound-p unbound-value)
+            (unbound-value (slot-definition-type slotd))
+          (let ((slot-name (slot-definition-name slotd)))
+            (when unbound-p
+              #'(lambda (object)
+                  (let ((value (funcall getter-function object)))
+                    (if (eq value unbound-value)
+                        (slot-unbound (class-of object) object slot-name)
+                        value)))))))
+       (getter-function)))))
+
+  (setf 
+   (slot-value slotd 'writer-function)
+   (if (not (slot-boundp slotd 'setter))
+       #'(lambda (object)
+          (declare (ignore object))
+          (error "Can't set slot: ~A" (slot-definition-name slotd)))
+     (with-slots (setter) slotd
+       (etypecase setter
+        (function setter)
+        ((or symbol cons) 
+         #'(lambda (value object)
+             (funcall (fdefinition setter) value object)))
+        (string
+         (let ((writer ()))
+           (setf
+            (slot-value slotd 'writer-function)
+            #'(lambda (value object)
+                (unless writer
+                  (setq writer
+                   (mkbinding setter 'nil 'pointer 
+                    (slot-definition-type slotd))))
+                (funcall writer (proxy-location object) value)))))))))
+
+  (initialize-internal-slot-gfs (slot-definition-name slotd)))
+
+
+
+(defmethod compute-slot-accessor-info ((slotd effective-virtual-slot-definition) type gf)
+  nil)
+
+(defmethod compute-effective-slot-definition-initargs ((class virtual-slots-class) direct-slotds)
+  (if (typep (first direct-slotds) 'direct-virtual-slot-definition)
+      (let ((initargs ()))
+       (let ((getter (most-specific-slot-value direct-slotds 'getter)))
+         (unless (eq getter *unbound-marker*)
+           (setf (getf initargs :getter) getter)))
+       (let ((setter (most-specific-slot-value direct-slotds 'setter)))
+         (unless (eq setter *unbound-marker*)
+           (setf (getf initargs :setter) setter)))
+       (let ((unbound (most-specific-slot-value direct-slotds 'unbound)))
+         (unless (eq unbound *unbound-marker*)
+           (setf (getf initargs :unbound) unbound)))
+       (let ((boundp (most-specific-slot-value direct-slotds 'boundp)))
+         (unless (eq boundp *unbound-marker*)
+           (setf (getf initargs :boundp) boundp)))
+       (nconc initargs (call-next-method)))
+    (call-next-method)))
+
 
 (defmethod slot-value-using-class
-    ((class virtual-slot-class) (object standard-object)
+    ((class virtual-slots-class) (object standard-object)
      (slotd effective-virtual-slot-definition))
-  (let ((reader (first (slot-definition-location slotd))))
-    (if reader
-       (funcall reader object)
-      (slot-unbound class object (slot-definition-name slotd)))))
+  (if (funcall (slot-value slotd 'boundp-function) object)
+      (funcall (slot-value slotd 'reader-function) object)
+    (slot-unbound class object (slot-definition-name slotd))))
 
 (defmethod slot-boundp-using-class
-    ((class virtual-slot-class) (object standard-object)
+    ((class virtual-slots-class) (object standard-object)
      (slotd effective-virtual-slot-definition))
-   (and (first (slot-definition-location slotd)) t))
-    
-(defmethod (setf slot-value-using-class)
-    (value (class virtual-slot-class) (object standard-object)
+  (funcall (slot-value slotd 'boundp-function) object))
+  
+(defmethod (setf slot-value-using-class) 
+    (value (class virtual-slots-class) (object standard-object)
      (slotd effective-virtual-slot-definition))
-  (let ((setter (second (slot-definition-location slotd))))
-    (cond
-     ((null setter)
-      (error
-       "Can't set read-only slot ~A in ~A"
-       (slot-definition-name slotd)
-       object))
-     ((or (functionp setter) (symbolp setter))
-      (funcall setter value object)
-      value)
-     (t
-      (funcall (fdefinition setter) value object)
-      value))))
-       
+  (funcall (slot-value slotd 'writer-function) value object))
+
+  
 (defmethod validate-superclass
-    ((class virtual-slot-class) (super pcl::standard-class))
+    ((class virtual-slots-class) (super standard-class))
   t)
 
 
@@ -116,271 +223,313 @@ (defvar *instance-cache* (make-hash-table :test #'eql))
 
 (defun cache-instance (instance)
   (setf
-   (gethash (system:sap-int (proxy-location instance)) *instance-cache*)
-   (ext:make-weak-pointer instance)))
+   (gethash (sap-int (proxy-location instance)) *instance-cache*)
+   (make-weak-pointer instance)))
 
 (defun find-cached-instance (location)
-  (let ((ref (gethash (system:sap-int location) *instance-cache*)))
+  (let ((ref (gethash (sap-int location) *instance-cache*)))
     (when ref
-      (ext:weak-pointer-value ref))))
+      (weak-pointer-value ref))))
+
+(defun instance-cached-p (location)
+  (gethash (sap-int location) *instance-cache*))
 
 (defun remove-cached-instance (location)
-  (remhash (system:sap-int location) *instance-cache*))
+  (remhash (sap-int location) *instance-cache*))
 
+;; For debuging
+(defun cached-instances ()
+  (let ((instances ()))
+    (maphash #'(lambda (location ref)
+                (declare (ignore location))
+                (push (weak-pointer-value ref) instances))
+            *instance-cache*)
+    instances))
+                       
 
 
 ;;;; Proxy for alien instances
 
-(eval-when (:compile-toplevel :load-toplevel :execute)
-  (defclass proxy ()
-    ((location :reader proxy-location :type system-area-pointer)))
+(defclass proxy ()
+  ((location :reader proxy-location :type system-area-pointer)))
 
-  (defgeneric initialize-proxy (object &rest initargs))
-  (defgeneric instance-finalizer (object)))
+(defgeneric initialize-proxy (object &rest initargs))
+(defgeneric instance-finalizer (object))
+(defgeneric reference-foreign (class location))
+(defgeneric unreference-foreign (class location))
 
+(defmethod reference-foreign ((name symbol) location)
+  (reference-foreign (find-class name) location))
 
-(defmethod initialize-instance :after ((instance proxy)
-                                      &rest initargs &key)
-  (declare (ignore initargs))
-  (cache-instance instance)
-  (ext:finalize instance (instance-finalizer instance)))
+(defmethod unreference-foreign ((name symbol) location)
+  (unreference-foreign (find-class name) location))
 
-(defmethod initialize-proxy ((instance proxy)
-                            &rest initargs &key location weak-ref)
-  (declare (ignore initargs))
-  (setf 
-   (slot-value instance 'location)
-   (if weak-ref
-       (funcall
-       (proxy-class-copy (class-of instance))
-       (type-of instance) location)
-     location))
+(defmethod unreference-foreign :around ((class class) location)
+  (unless (null-pointer-p location)
+;;     (format t "Unreferencing ~A at ~A" (class-name class) location)
+;;     (finish-output *standard-output*)
+    (call-next-method)
+;;     (write-line " done")
+;;     (finish-output *standard-output*)
+    ))
+
+(defmethod print-object ((instance proxy) stream)
+  (print-unreadable-object (instance stream :type t :identity nil)
+    (when (slot-boundp instance 'location)
+      (format stream "at 0x~X" (sap-int (proxy-location instance))))))
+
+(defmethod initialize-instance :around ((instance proxy) &key location)
+  (if location
+      (setf (slot-value instance 'location) location)      
+    (call-next-method))
   (cache-instance instance)
-  (ext:finalize instance (instance-finalizer instance)))
+  (finalize instance (instance-finalizer instance))
+  instance)
 
 (defmethod instance-finalizer ((instance proxy))
-  (let ((free (proxy-class-free (class-of instance)))
-       (type (type-of instance))
-       (location (proxy-location instance)))
-    (declare
-     (type symbol type)
-     (type system-area-pointer location))
+  (let ((location (proxy-location instance))
+       (class (class-of instance)))    
+;;     (unless (find-method #'unreference-foreign nil (list (class-of class) t) nil)
+;;       (error "No matching method for UNREFERENCE-INSTANCE when called with class ~A" class))
     #'(lambda ()
-       (funcall free type location)
-       (remove-cached-instance location))))
+       (remove-cached-instance location)
+       (unreference-foreign class location))))
 
 
-(deftype-method translate-type-spec proxy (type-spec)
-  (declare (ignore type-spec))
-  (translate-type-spec 'pointer))
-
-(deftype-method size-of proxy (type-spec)
-  (declare (ignore type-spec))
-  (size-of 'pointer))
-
-(deftype-method translate-from-alien
-    proxy (type-spec location &optional weak-ref)
-  `(let ((location ,location))
-     (unless (null-pointer-p location)
-       (ensure-proxy-instance ',type-spec location ,weak-ref))))
-
-(deftype-method translate-to-alien
-    proxy (type-spec instance &optional weak-ref)
-  (if weak-ref
-      `(proxy-location ,instance)
-    `(funcall
-      ',(proxy-class-copy (find-class type-spec))
-      ',type-spec (proxy-location ,instance))))
-
-(deftype-method unreference-alien proxy (type-spec location)
-  `(funcall ',(proxy-class-free (find-class type-spec)) ',type-spec ,location))
-
-(defun proxy-instance-size (proxy)
-  (proxy-class-size (class-of proxy)))
-
 ;;;; Metaclass used for subclasses of proxy
 
+(defgeneric most-specific-proxy-superclass (class))
+(defgeneric direct-proxy-superclass (class))
+  
+
 (eval-when (:compile-toplevel :load-toplevel :execute)
-  (defclass proxy-class (virtual-slot-class)
-    ((size :reader proxy-class-size)
-     (copy :reader proxy-class-copy)
-     (free :reader proxy-class-free)))
+  (defclass proxy-class (virtual-slots-class)
+    ((size :reader proxy-instance-size)))
 
   (defclass direct-alien-slot-definition (direct-virtual-slot-definition)
     ((allocation :initform :alien)
      (offset :reader slot-definition-offset :initarg :offset)))
   
   (defclass effective-alien-slot-definition (effective-virtual-slot-definition)
-    ((offset :reader slot-definition-offset)))
-  
-  (defclass effective-virtual-alien-slot-definition
-    (effective-virtual-slot-definition))
-
+    ((offset :reader slot-definition-offset :initarg :offset)))
 
   (defmethod most-specific-proxy-superclass ((class proxy-class))
     (find-if
      #'(lambda (class)
         (subtypep (class-name class) 'proxy))
-     (cdr (pcl::compute-class-precedence-list class))))
+     (cdr (compute-class-precedence-list class))))
 
   (defmethod direct-proxy-superclass ((class proxy-class))
     (find-if
      #'(lambda (class)
         (subtypep (class-name class) 'proxy))
-     (pcl::class-direct-superclasses class)))
-
-  (defmethod shared-initialize ((class proxy-class) names
-                               &rest initargs &key size copy free)
-    (declare (ignore initargs))
+     (class-direct-superclasses class)))
+  
+  (defmethod shared-initialize ((class proxy-class) names &key size)
     (call-next-method)
     (cond
-     (size (setf (slot-value class 'size) (first size)))
-     ((slot-boundp class 'size) (slot-makunbound class 'size)))
-    (cond
-     (copy (setf (slot-value class 'copy) (first copy)))
-     ((slot-boundp class 'copy) (slot-makunbound class 'copy)))
-    (cond
-     (free (setf (slot-value class 'free) (first free)))
-     ((slot-boundp class 'free) (slot-makunbound class 'free))))
-
-  (defmethod finalize-inheritance ((class proxy-class))
-    (call-next-method)
-    (let ((super (most-specific-proxy-superclass class)))
-      (unless (or (not super) (eq super (find-class 'proxy)))
-       (unless (or (slot-boundp class 'copy) (not (slot-boundp super 'copy)))
-         (setf (slot-value class 'copy) (proxy-class-copy super)))
-       (unless (or (slot-boundp class 'free) (not (slot-boundp super 'free)))
-         (setf (slot-value class 'free) (proxy-class-free super))))))
-
-  (defmethod direct-slot-definition-class ((class proxy-class) initargs)
+      (size (setf (slot-value class 'size) (first size)))
+      ((slot-boundp class 'size) (slot-makunbound class 'size))))
+  
+  (defmethod direct-slot-definition-class ((class proxy-class) &rest initargs)
     (case (getf initargs :allocation)
       ((nil :alien) (find-class 'direct-alien-slot-definition))
-;      (:instance (error "Allocation :instance not allowed in class ~A" class))
       (t (call-next-method))))
-
-  (defmethod effective-slot-definition-class ((class proxy-class) initargs)
+  
+  (defmethod effective-slot-definition-class ((class proxy-class) &rest initargs)
     (case (getf initargs :allocation)
       (:alien (find-class 'effective-alien-slot-definition))
-      (:virtual (find-class 'effective-virtual-alien-slot-definition))
       (t (call-next-method))))
   
-  (defmethod compute-virtual-slot-accessors
-      ((class proxy-class) (slotd effective-alien-slot-definition)
-       direct-slotds)
-    (with-slots (offset type) slotd
-      (let ((reader (intern-reader-function type))
-           (writer (intern-writer-function type))
-           (destroy (intern-destroy-function type)))
-       (setf offset (slot-definition-offset (first direct-slotds)))
-       (list
-        #'(lambda (object)
-            (funcall reader (proxy-location object) offset))
-        #'(lambda (value object)
-            (let ((location (proxy-location object)))
-              (funcall destroy location offset)
-              (funcall writer value location offset)))))))
-  (defmethod compute-virtual-slot-accessors
-      ((class proxy-class)
-       (slotd effective-virtual-alien-slot-definition)
-       direct-slotds)
-    (destructuring-bind (getter setter) (call-next-method)
-      (with-slots (type) slotd
-       (list
-        (if (stringp getter)
-            (let ((getter (mkbinding-late getter type 'pointer)))
-              #'(lambda (object)
-                  (funcall getter (proxy-location object))))
-          getter)
-        (if (stringp setter)
-            (let ((setter (mkbinding-late setter 'nil 'pointer type)))
-              #'(lambda (value object)
-                  (funcall setter (proxy-location object) value)))
-          setter)))))
+  
+  (defmethod compute-effective-slot-definition-initargs ((class proxy-class) direct-slotds)
+    (if (eq (most-specific-slot-value direct-slotds 'allocation) :alien)
+       (nconc 
+        (list :offset (most-specific-slot-value direct-slotds 'offset))
+        (call-next-method))
+      (call-next-method)))
+  
+
+  (defmethod initialize-internal-slot-functions ((slotd effective-alien-slot-definition))
+    (with-slots (offset) slotd
+      (let ((type (slot-definition-type slotd)))
+       (unless (slot-boundp slotd 'getter)
+         (let ((reader (reader-function type)))
+           (setf 
+            (slot-value slotd 'getter)
+            #'(lambda (object)
+                (funcall reader (proxy-location object) offset)))))
+
+       (unless (slot-boundp slotd 'setter)
+         (let ((writer (writer-function type))
+               (destroy (destroy-function type)))
+           (setf 
+            (slot-value slotd 'setter)
+            #'(lambda (value object)
+                (let ((location (proxy-location object)))
+                  (funcall destroy location offset) ; destroy old value
+                  (funcall writer value location offset))))))))
+
+    (call-next-method))
+  
+
+  ;; TODO: call some C code to detect this a compile time
+  (defconstant +struct-alignmen+ 4)
 
   (defmethod compute-slots ((class proxy-class))
-    (with-slots (direct-slots size) class
-      (let ((current-offset
-            (proxy-class-size (most-specific-proxy-superclass class)))
-           (max-size 0))
-       (dolist (slotd direct-slots)
-         (when (eq (slot-definition-allocation slotd) :alien)
-           (with-slots (offset type) slotd
-             (unless (slot-boundp slotd 'offset)
-               (setf offset current-offset))
-             (setq current-offset (+ offset (size-of type)))
-             (setq max-size (max max-size current-offset)))))
-       (unless (slot-boundp class 'size)
-         (setf size max-size))))
+    (loop 
+     with offset = (let ((size-of-super-classes
+                         (proxy-instance-size 
+                          (most-specific-proxy-superclass class))))
+                    (+ size-of-super-classes 
+                       (mod size-of-super-classes +struct-alignmen+)))
+     with size = offset
+     for slotd in (class-direct-slots class)
+     when (eq (slot-definition-allocation slotd) :alien)
+     do (if (not (slot-boundp slotd 'offset))
+           (setf (slot-value slotd 'offset) offset)
+         (setq offset (slot-value slotd 'offset)))
+
+        (incf offset (size-of (slot-definition-type slotd)))
+       (incf offset (mod offset +struct-alignmen+))
+       (setq size (max size offset))
+
+     finally (unless (slot-boundp class 'size)
+              (setf (slot-value class 'size) size)))
     (call-next-method))
-   
-  (defmethod validate-superclass ((class proxy-class)
-                                 (super pcl::standard-class))
-    (subtypep (class-name super) 'proxy))
 
-  (defmethod proxy-class-size (class)
+  
+  (defmethod validate-superclass ((class proxy-class) (super standard-class))
+    (subtypep (class-name super) 'proxy))
+  
+  (defmethod proxy-instance-size (class)
     (declare (ignore class))
     0)
 
-  (defgeneric make-proxy-instance (class location weak-ref
-                                  &rest initargs &key)))
-
-(defmethod make-proxy-instance ((class symbol) location weak-ref
-                               &rest initargs &key)
-  (apply #'make-proxy-instance (find-class class) location weak-ref initargs))
+  (defmethod proxy-instance-size ((class-name symbol))
+    (proxy-instance-size (find-class class-name)))
+)
+  
+(defmethod alien-type ((class proxy-class) &rest args)
+  (declare (ignore class args))
+  (alien-type 'pointer))
 
-(defmethod make-proxy-instance ((class proxy-class) location weak-ref
-                               &rest initargs &key)
-  (let ((instance (allocate-instance class)))
-    (apply
-     #'initialize-proxy
-     instance :location location :weak-ref weak-ref initargs)
-    instance))
+(defmethod size-of ((class proxy-class) &rest args)
+  (declare (ignore class args))
+  (size-of 'pointer))
 
-(defun ensure-proxy-instance (class location weak-ref &rest initargs)
-  (or
-   (find-cached-instance location)
-   (apply #'make-proxy-instance class location weak-ref initargs)))
+(defmethod from-alien-form (location (class proxy-class) &rest args)
+  (declare (ignore args))
+  `(ensure-proxy-instance ',(class-name class) ,location))
+
+(defmethod from-alien-function ((class proxy-class) &rest args)
+  (declare (ignore args))  
+  #'(lambda (location)
+      (ensure-proxy-instance class location)))
+
+(defmethod to-alien-form (instance (class proxy-class) &rest args)
+  (declare (ignore class args))
+  `(proxy-location ,instance))
+
+(defmethod to-alien-function ((class proxy-class) &rest args)
+  (declare (ignore class args))
+  #'proxy-location)
+
+(defmethod copy-from-alien-form (location (class proxy-class) &rest args)
+  (declare (ignore args))
+  (let ((class-name (class-name class)))
+    `(ensure-proxy-instance ',class-name
+      (reference-foreign ',class-name ,location))))
+
+(defmethod copy-from-alien-function ((class proxy-class) &rest args)
+  (declare (ignore args))  
+  #'(lambda (location)
+      (ensure-proxy-instance class (reference-foreign class location))))
+
+(defmethod copy-to-alien-form (instance (class proxy-class) &rest args)
+  (declare (ignore args))
+  `(reference-foreign ',(class-name class) (proxy-location ,instance)))
+
+(defmethod copy-to-alien-function ((class proxy-class) &rest args)
+  (declare (ignore args))
+  #'(lambda (instance)
+      (reference-foreign class (proxy-location instance))))
+
+(defmethod writer-function ((class proxy-class) &rest args)
+  (declare (ignore args))
+  #'(lambda (instance location &optional (offset 0))
+      (assert (null-pointer-p (sap-ref-sap location offset)))
+      (setf 
+       (sap-ref-sap location offset)
+       (reference-foreign class (proxy-location instance)))))
+
+(defmethod reader-function ((class proxy-class) &rest args)
+  (declare (ignore args))
+  #'(lambda (location &optional (offset 0))
+      (let ((instance (sap-ref-sap location offset)))
+       (unless (null-pointer-p instance)
+         (ensure-proxy-instance class (reference-foreign class instance))))))
+
+(defmethod destroy-function ((class proxy-class) &rest args)
+  (declare (ignore args))
+  #'(lambda (location &optional (offset 0))
+      (unreference-foreign class (sap-ref-sap location offset))))
+
+(defmethod unbound-value ((class proxy-class) &rest args)
+  (declare (ignore args))
+  (values t nil))
+
+(defgeneric ensure-proxy-instance (class location)
+  (:documentation "Returns a proxy object representing the foreign object at the give location."))
+
+(defmethod ensure-proxy-instance :around (class location)
+  (unless (null-pointer-p location)
+    (or 
+     (find-cached-instance location)
+     (call-next-method))))
+  
+(defmethod ensure-proxy-instance ((class symbol) location)
+  (ensure-proxy-instance (find-class class) location))
 
+(defmethod ensure-proxy-instance ((class proxy-class) location)
+  (make-instance class :location location))
 
 
 ;;;; Superclasses for wrapping of C structures
 
-(eval-when (:compile-toplevel :load-toplevel :execute)
-  (defclass struct (proxy)
-    ()
-    (:metaclass proxy-class)
-    (:copy %copy-struct)
-    (:free %free-struct)))
-
-(defmethod initialize-instance ((structure struct)
-                               &rest initargs)
+(defclass struct (proxy)
+  ()
+  (:metaclass proxy-class))
+
+(defmethod initialize-instance ((struct struct) &rest initargs)
   (declare (ignore initargs))
-  (setf 
-   (slot-value structure 'location)
-   (allocate-memory (proxy-class-size (class-of structure))))
+  (unless (slot-boundp struct 'location)
+    (let ((size (proxy-instance-size (class-of struct))))
+      (if (zerop size)
+         (error "~A has zero size" (class-of struct))
+       (setf (slot-value struct 'location) (allocate-memory size)))))
   (call-next-method))
 
 
-(defun %copy-struct (type location)
-  (copy-memory location (proxy-class-size (find-class type))))
+;;;; Metaclasses used for subclasses of struct
+
+(defclass struct-class (proxy-class)
+  ())
+
+(defmethod reference-foreign ((class struct-class) location)
+  (copy-memory location (proxy-instance-size class)))
 
-(defun %free-struct (type location)
-  (declare (ignore type))
+(defmethod unreference-foreign ((class struct-class) location)
   (deallocate-memory location))
 
 
-;(eval-when (:compile-toplevel :load-toplevel :execute)
-  (defclass static (struct)
-    ()
-    (:metaclass proxy-class)
-    (:copy %copy-static)
-    (:free %free-static));)
+(defclass static-struct-class (struct-class)
+  ())
 
-(defun %copy-static (type location)
-  (declare (ignore type))
+(defmethod reference-foreign ((class static-struct-class) location)
+  (declare (ignore class))
   location)
 
-(defun %free-static (type location)
-  (declare (ignore type location))
+(defmethod unreference-foreign ((class static-struct-class) location)
+  (declare (ignore class location))
   nil)