Report the faulty keyword in errors raised by `scm_c_bind_keyword_arguments'.
[bpt/guile.git] / libguile / foreign.c
index aae4c67..90a4fca 100644 (file)
@@ -1,5 +1,5 @@
-/* Copyright (C) 2010  Free Software Foundation, Inc.
- * 
+/* Copyright (C) 2010, 2011, 2012, 2013  Free Software Foundation, Inc.
+ *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public License
  * as published by the Free Software Foundation; either version 3 of
@@ -22,6 +22,7 @@
 
 #include <ffi.h>
 
+#include <alloca.h>
 #include <alignof.h>
 #include <string.h>
 #include <assert.h>
@@ -29,6 +30,7 @@
 #include "libguile/_scm.h"
 #include "libguile/bytevectors.h"
 #include "libguile/instructions.h"
+#include "libguile/threads.h"
 #include "libguile/foreign.h"
 
 \f
@@ -44,11 +46,15 @@ SCM_SYMBOL (sym_uint32, "uint32");
 SCM_SYMBOL (sym_int32, "int32");
 SCM_SYMBOL (sym_uint64, "uint64");
 SCM_SYMBOL (sym_int64, "int64");
+SCM_SYMBOL (sym_short, "short");
 SCM_SYMBOL (sym_int, "int");
 SCM_SYMBOL (sym_long, "long");
+SCM_SYMBOL (sym_unsigned_short, "unsigned-short");
 SCM_SYMBOL (sym_unsigned_int, "unsigned-int");
 SCM_SYMBOL (sym_unsigned_long, "unsigned-long");
 SCM_SYMBOL (sym_size_t, "size_t");
+SCM_SYMBOL (sym_ssize_t, "ssize_t");
+SCM_SYMBOL (sym_ptrdiff_t, "ptrdiff_t");
 
 /* that's for pointers, you know. */
 SCM_SYMBOL (sym_asterisk, "*");
@@ -59,6 +65,17 @@ SCM_SYMBOL (sym_null_pointer_error, "null-pointer-error");
 /* The cell representing the null pointer.  */
 static SCM null_pointer;
 
+#if SIZEOF_VOID_P == 4
+# define scm_to_uintptr   scm_to_uint32
+# define scm_from_uintptr scm_from_uint32
+#elif SIZEOF_VOID_P == 8
+# define scm_to_uintptr   scm_to_uint64
+# define scm_from_uintptr scm_from_uint64
+#else
+# error unsupported pointer size
+#endif
+
+
 /* Raise a null pointer dereference error.  */
 static void
 null_pointer_error (const char *func_name)
@@ -71,184 +88,148 @@ null_pointer_error (const char *func_name)
 static SCM cif_to_procedure (SCM cif, SCM func_ptr);
 
 
-static SCM foreign_weak_refs = SCM_BOOL_F;
+static SCM pointer_weak_refs = SCM_BOOL_F;
+static scm_i_pthread_mutex_t weak_refs_lock = SCM_I_PTHREAD_MUTEX_INITIALIZER;
+
 
 static void
 register_weak_reference (SCM from, SCM to)
 {
-  scm_hashq_set_x (foreign_weak_refs, from, to);
+  scm_i_pthread_mutex_lock (&weak_refs_lock);
+  scm_hashq_set_x (pointer_weak_refs, from, to);
+  scm_i_pthread_mutex_unlock (&weak_refs_lock);
 }
-    
+
 static void
-foreign_finalizer_trampoline (GC_PTR ptr, GC_PTR data)
+pointer_finalizer_trampoline (void *ptr, void *data)
 {
-  scm_t_foreign_finalizer finalizer = data;
-  finalizer (SCM_FOREIGN_POINTER (PTR2SCM (ptr), void));
+  scm_t_pointer_finalizer finalizer = data;
+  finalizer (SCM_POINTER_VALUE (PTR2SCM (ptr)));
 }
 
-SCM
-scm_take_foreign_pointer (scm_t_foreign_type type, void *ptr, size_t len,
-                          scm_t_foreign_finalizer finalizer)
+SCM_DEFINE (scm_pointer_p, "pointer?", 1, 0, 0,
+           (SCM obj),
+           "Return @code{#t} if @var{obj} is a pointer object, "
+           "@code{#f} otherwise.\n")
+#define FUNC_NAME s_scm_pointer_p
 {
-  SCM ret;
-  scm_t_bits word0;
-    
-  word0 = (scm_t_bits)(scm_tc7_foreign | (type<<8)
-                       | (finalizer ? (1<<16) : 0) | (len<<17));
-  if (SCM_UNLIKELY ((word0 >> 17) != len))
-    scm_out_of_range ("scm_take_foreign_pointer", scm_from_size_t (len));
+  return scm_from_bool (SCM_POINTER_P (obj));
+}
+#undef FUNC_NAME
 
-  ret = scm_cell (word0, (scm_t_bits) ptr);
-  if (finalizer)
+SCM_DEFINE (scm_make_pointer, "make-pointer", 1, 1, 0,
+           (SCM address, SCM finalizer),
+           "Return a foreign pointer object pointing to @var{address}. "
+           "If @var{finalizer} is passed, it should be a pointer to a "
+           "one-argument C function that will be called when the pointer "
+           "object becomes unreachable.")
+#define FUNC_NAME s_scm_make_pointer
+{
+  void *c_finalizer;
+  scm_t_uintptr c_address;
+
+  c_address = scm_to_uintptr (address);
+  if (SCM_UNBNDP (finalizer))
+    c_finalizer = NULL;
+  else
     {
-      /* Register a finalizer for the newly created instance.  */
-      GC_finalization_proc prev_finalizer;
-      GC_PTR prev_finalizer_data;
-      GC_REGISTER_FINALIZER_NO_ORDER (SCM2PTR (ret),
-                                      foreign_finalizer_trampoline,
-                                      finalizer,
-                                      &prev_finalizer,
-                                      &prev_finalizer_data);
+      SCM_VALIDATE_POINTER (2, finalizer);
+      c_finalizer = SCM_POINTER_VALUE (finalizer);
     }
 
-  return ret;
+  return scm_from_pointer ((void *) c_address, c_finalizer);
 }
+#undef FUNC_NAME
 
-SCM_DEFINE (scm_foreign_ref, "foreign-ref", 1, 0, 0,
-           (SCM foreign),
-           "Reference the foreign value pointed to by @var{foreign}.\n\n"
-            "The value will be referenced according to its type.")
-#define FUNC_NAME s_scm_foreign_ref
+void *
+scm_to_pointer (SCM pointer)
+#define FUNC_NAME "scm_to_pointer"
 {
-  scm_t_foreign_type ftype;
-  scm_t_uint8 *ptr;
+  SCM_VALIDATE_POINTER (1, pointer);
+  return SCM_POINTER_VALUE (pointer);
+}
+#undef FUNC_NAME
 
-  SCM_VALIDATE_FOREIGN (1, foreign);
-  ptr = SCM_FOREIGN_POINTER (foreign, scm_t_uint8);
-  ftype = SCM_FOREIGN_TYPE (foreign);
-  
-  /* FIXME: is there a window in which we can see ptr but not foreign? */
-  /* FIXME: accessing unaligned pointers */
-  switch (ftype)
+SCM
+scm_from_pointer (void *ptr, scm_t_pointer_finalizer finalizer)
+{
+  SCM ret;
+
+  if (ptr == NULL && finalizer == NULL)
+    ret = null_pointer;
+  else
     {
-    case SCM_FOREIGN_TYPE_VOID:
-      return scm_from_ulong ((unsigned long)ptr);
-    case SCM_FOREIGN_TYPE_FLOAT:
-      return scm_from_double (*(float*)ptr);
-    case SCM_FOREIGN_TYPE_DOUBLE:
-      return scm_from_double (*(double*)ptr);
-    case SCM_FOREIGN_TYPE_UINT8:
-      return scm_from_uint8 (*(scm_t_uint8*)ptr);
-    case SCM_FOREIGN_TYPE_INT8:
-      return scm_from_int8 (*(scm_t_int8*)ptr);
-    case SCM_FOREIGN_TYPE_UINT16:
-      return scm_from_uint16 (*(scm_t_uint16*)ptr);
-    case SCM_FOREIGN_TYPE_INT16:
-      return scm_from_int16 (*(scm_t_int16*)ptr);
-    case SCM_FOREIGN_TYPE_UINT32:
-      return scm_from_uint32 (*(scm_t_uint32*)ptr);
-    case SCM_FOREIGN_TYPE_INT32:
-      return scm_from_int32 (*(scm_t_int32*)ptr);
-    case SCM_FOREIGN_TYPE_UINT64:
-      return scm_from_uint64 (*(scm_t_uint64*)ptr);
-    case SCM_FOREIGN_TYPE_INT64:
-      return scm_from_int64 (*(scm_t_int64*)ptr);
-    default:
-      scm_wrong_type_arg_msg (FUNC_NAME, 1, foreign, "foreign");
+      ret = scm_cell (scm_tc7_pointer, (scm_t_bits) ptr);
+
+      if (finalizer)
+        scm_i_set_finalizer (SCM2PTR (ret), pointer_finalizer_trampoline,
+                             finalizer);
     }
+
+  return ret;
 }
-#undef FUNC_NAME
 
-SCM_DEFINE (scm_foreign_set_x, "foreign-set!", 2, 0, 0,
-           (SCM foreign, SCM val),
-           "Set the foreign value pointed to by @var{foreign}.\n\n"
-            "The value will be set according to its type.")
-#define FUNC_NAME s_scm_foreign_set_x
+SCM_DEFINE (scm_pointer_address, "pointer-address", 1, 0, 0,
+           (SCM pointer),
+           "Return the numerical value of @var{pointer}.")
+#define FUNC_NAME s_scm_pointer_address
 {
-  scm_t_foreign_type ftype;
-  scm_t_uint8 *ptr;
+  SCM_VALIDATE_POINTER (1, pointer);
 
-  SCM_VALIDATE_FOREIGN (1, foreign);
+  return scm_from_uintptr ((scm_t_uintptr) SCM_POINTER_VALUE (pointer));
+}
+#undef FUNC_NAME
 
-  if (SCM_UNLIKELY (scm_is_eq (foreign, null_pointer)))
-    /* Attempting to modify the pointer value of NULL_POINTER (which is
-       read-only anyway), so raise an error.  */
-    null_pointer_error (FUNC_NAME);
+SCM_DEFINE (scm_pointer_to_scm, "pointer->scm", 1, 0, 0,
+           (SCM pointer),
+           "Unsafely cast @var{pointer} to a Scheme object.\n"
+           "Cross your fingers!")
+#define FUNC_NAME s_scm_pointer_to_scm
+{
+  SCM_VALIDATE_POINTER (1, pointer);
+  
+  return SCM_PACK ((scm_t_bits) SCM_POINTER_VALUE (pointer));
+}
+#undef FUNC_NAME
 
-  ptr = SCM_FOREIGN_POINTER (foreign, scm_t_uint8);
-  ftype = SCM_FOREIGN_TYPE (foreign);
+SCM_DEFINE (scm_scm_to_pointer, "scm->pointer", 1, 0, 0,
+           (SCM scm),
+           "Return a foreign pointer object with the @code{object-address}\n"
+            "of @var{scm}.")
+#define FUNC_NAME s_scm_scm_to_pointer
+{
+  SCM ret;
 
-  /* FIXME: is there a window in which we can see ptr but not foreign? */
-  /* FIXME: unaligned access */
-  switch (ftype)
-    {
-    case SCM_FOREIGN_TYPE_VOID:
-      SCM_SET_CELL_WORD_1 (foreign, scm_to_ulong (val));
-      break;
-    case SCM_FOREIGN_TYPE_FLOAT:
-      *(float*)ptr = scm_to_double (val);
-      break;
-    case SCM_FOREIGN_TYPE_DOUBLE:
-      *(double*)ptr = scm_to_double (val);
-      break;
-    case SCM_FOREIGN_TYPE_UINT8:
-      *(scm_t_uint8*)ptr = scm_to_uint8 (val);
-      break;
-    case SCM_FOREIGN_TYPE_INT8:
-      *(scm_t_int8*)ptr = scm_to_int8 (val);
-      break;
-    case SCM_FOREIGN_TYPE_UINT16:
-      *(scm_t_uint16*)ptr = scm_to_uint16 (val);
-      break;
-    case SCM_FOREIGN_TYPE_INT16:
-      *(scm_t_int16*)ptr = scm_to_int16 (val);
-      break;
-    case SCM_FOREIGN_TYPE_UINT32:
-      *(scm_t_uint32*)ptr = scm_to_uint32 (val);
-      break;
-    case SCM_FOREIGN_TYPE_INT32:
-      *(scm_t_int32*)ptr = scm_to_int32 (val);
-      break;
-    case SCM_FOREIGN_TYPE_UINT64:
-      *(scm_t_uint64*)ptr = scm_to_uint64 (val);
-      break;
-    case SCM_FOREIGN_TYPE_INT64:
-      *(scm_t_int64*)ptr = scm_to_int64 (val);
-      break;
-    default:
-      scm_wrong_type_arg_msg (FUNC_NAME, 1, val, "foreign");
-    }
+  ret = scm_from_pointer ((void*) SCM_UNPACK (scm), NULL);
+  if (SCM_NIMP (ret))
+    register_weak_reference (ret, scm);
 
-  return SCM_UNSPECIFIED;
+  return ret;
 }
 #undef FUNC_NAME
 
-SCM_DEFINE (scm_foreign_to_bytevector, "foreign->bytevector", 1, 3, 0,
-           (SCM foreign, SCM uvec_type, SCM offset, SCM len),
-           "Return a bytevector aliasing the memory pointed to by\n"
-            "@var{foreign}.\n\n"
-            "@var{foreign} must be a void pointer, a foreign whose type is\n"
-            "@var{void}. By default, the resulting bytevector will alias\n"
-            "all of the memory pointed to by @var{foreign}, from beginning\n"
-            "to end, treated as a @code{vu8} array.\n\n"
+SCM_DEFINE (scm_pointer_to_bytevector, "pointer->bytevector", 2, 2, 0,
+           (SCM pointer, SCM len, SCM offset, SCM uvec_type),
+           "Return a bytevector aliasing the @var{len} bytes pointed\n"
+           "to by @var{pointer}.\n\n"
             "The user may specify an alternate default interpretation for\n"
             "the memory by passing the @var{uvec_type} argument, to indicate\n"
             "that the memory is an array of elements of that type.\n"
             "@var{uvec_type} should be something that\n"
             "@code{uniform-vector-element-type} would return, like @code{f32}\n"
             "or @code{s16}.\n\n"
-            "Users may also specify that the bytevector should only alias a\n"
-            "subset of the memory, by specifying @var{offset} and @var{len}\n"
-            "arguments.")
-#define FUNC_NAME s_scm_foreign_to_bytevector
+           "When @var{offset} is passed, it specifies the offset in bytes\n"
+           "relative to @var{pointer} of the memory region aliased by the\n"
+           "returned bytevector.")
+#define FUNC_NAME s_scm_pointer_to_bytevector
 {
   SCM ret;
   scm_t_int8 *ptr;
   size_t boffset, blen;
   scm_t_array_element_type btype;
 
-  SCM_VALIDATE_FOREIGN_TYPED (1, foreign, VOID);
-  ptr = SCM_FOREIGN_POINTER (foreign, scm_t_int8);
+  SCM_VALIDATE_POINTER (1, pointer);
+  ptr = SCM_POINTER_VALUE (pointer);
 
   if (SCM_UNLIKELY (ptr == NULL))
     null_pointer_error (FUNC_NAME);
@@ -283,153 +264,172 @@ SCM_DEFINE (scm_foreign_to_bytevector, "foreign->bytevector", 1, 3, 0,
                                   "uniform vector type");
         }
     }
-  
+
   if (SCM_UNBNDP (offset))
     boffset = 0;
-  else if (SCM_FOREIGN_LEN (foreign))
-    boffset = scm_to_unsigned_integer (offset, 0,
-                                       SCM_FOREIGN_LEN (foreign) - 1);
   else
     boffset = scm_to_size_t (offset);
 
-  if (SCM_UNBNDP (len))
-    {
-      if (SCM_FOREIGN_LEN (foreign))
-        blen = SCM_FOREIGN_LEN (foreign) - boffset;
-      else
-        scm_misc_error (FUNC_NAME,
-                        "length needed to convert foreign pointer to bytevector",
-                        SCM_EOL);
-    }
-  else
-    {
-      if (SCM_FOREIGN_LEN (foreign))
-        blen = scm_to_unsigned_integer (len, 0,
-                                        SCM_FOREIGN_LEN (foreign) - boffset);
-      else
-        blen = scm_to_size_t (len);
-    }
+  blen = scm_to_size_t (len);
 
-  ret = scm_c_take_typed_bytevector (ptr + boffset, blen, btype);
-  register_weak_reference (ret, foreign);
+  ret = scm_c_take_typed_bytevector ((signed char *) ptr + boffset,
+                                    blen, btype);
+  register_weak_reference (ret, pointer);
   return ret;
 }
 #undef FUNC_NAME
 
-SCM_DEFINE (scm_bytevector_to_foreign, "bytevector->foreign", 1, 2, 0,
-           (SCM bv, SCM offset, SCM len),
-           "Return a foreign pointer aliasing the memory pointed to by\n"
-            "@var{bv}.\n\n"
-            "The resulting foreign will be a void pointer, a foreign whose\n"
-            "type is @code{void}. By default it will alias all of the\n"
-            "memory pointed to by @var{bv}, from beginning to end.\n\n"
-            "Users may explicily specify that the foreign should only alias a\n"
-            "subset of the memory, by specifying @var{offset} and @var{len}\n"
-            "arguments.")
-#define FUNC_NAME s_scm_bytevector_to_foreign
+SCM_DEFINE (scm_bytevector_to_pointer, "bytevector->pointer", 1, 1, 0,
+           (SCM bv, SCM offset),
+           "Return a pointer pointer aliasing the memory pointed to by\n"
+            "@var{bv} or @var{offset} bytes after @var{bv} when @var{offset}\n"
+           "is passed.")
+#define FUNC_NAME s_scm_bytevector_to_pointer
 {
   SCM ret;
-  scm_t_int8 *ptr;
-  size_t boffset, blen;
+  signed char *ptr;
+  size_t boffset;
 
   SCM_VALIDATE_BYTEVECTOR (1, bv);
   ptr = SCM_BYTEVECTOR_CONTENTS (bv);
-  
+
   if (SCM_UNBNDP (offset))
     boffset = 0;
   else
     boffset = scm_to_unsigned_integer (offset, 0,
                                        SCM_BYTEVECTOR_LENGTH (bv) - 1);
 
-  if (SCM_UNBNDP (len))
-    blen = SCM_BYTEVECTOR_LENGTH (bv) - boffset;
-  else
-    blen = scm_to_unsigned_integer (len, 0,
-                                    SCM_BYTEVECTOR_LENGTH (bv) - boffset);
-
-  ret = scm_take_foreign_pointer (SCM_FOREIGN_TYPE_VOID, ptr + boffset, blen,
-                                  NULL);
+  ret = scm_from_pointer (ptr + boffset, NULL);
   register_weak_reference (ret, bv);
   return ret;
 }
 #undef FUNC_NAME
 
-SCM_DEFINE (scm_foreign_set_finalizer_x, "foreign-set-finalizer!", 2, 0, 0,
-            (SCM foreign, SCM finalizer),
+SCM_DEFINE (scm_set_pointer_finalizer_x, "set-pointer-finalizer!", 2, 0, 0,
+            (SCM pointer, SCM finalizer),
             "Arrange for the C procedure wrapped by @var{finalizer} to be\n"
-            "called on the pointer wrapped by @var{foreign} when @var{foreign}\n"
+            "called on the pointer wrapped by @var{pointer} when @var{pointer}\n"
             "becomes unreachable. Note: the C procedure should not call into\n"
             "Scheme. If you need a Scheme finalizer, use guardians.")
-#define FUNC_NAME s_scm_foreign_set_finalizer_x
+#define FUNC_NAME s_scm_set_pointer_finalizer_x
 {
-  void *c_finalizer;
-  GC_finalization_proc prev_finalizer;
-  GC_PTR prev_finalizer_data;
+  SCM_VALIDATE_POINTER (1, pointer);
+  SCM_VALIDATE_POINTER (2, finalizer);
 
-  SCM_VALIDATE_FOREIGN_TYPED (1, foreign, VOID);
-  SCM_VALIDATE_FOREIGN_TYPED (2, finalizer, VOID);
-  
-  c_finalizer = SCM_FOREIGN_POINTER (finalizer, void);
-
-  SCM_SET_CELL_WORD_0 (foreign, SCM_CELL_WORD_0 (foreign) | (1<<16));
-
-  GC_REGISTER_FINALIZER_NO_ORDER (SCM2PTR (foreign),
-                                  foreign_finalizer_trampoline,
-                                  c_finalizer,
-                                  &prev_finalizer,
-                                  &prev_finalizer_data);
+  scm_i_add_finalizer (SCM2PTR (pointer), pointer_finalizer_trampoline,
+                       SCM_POINTER_VALUE (finalizer));
 
   return SCM_UNSPECIFIED;
 }
 #undef FUNC_NAME
 
+void
+scm_i_pointer_print (SCM pointer, SCM port, scm_print_state *pstate)
+{
+  scm_puts ("#<pointer 0x", port);
+  scm_uintprint (scm_to_uintptr (scm_pointer_address (pointer)), 16, port);
+  scm_putc ('>', port);
+}
+
 \f
+/* Non-primitive helpers functions.  These procedures could be
+   implemented in terms of the primitives above but would be inefficient
+   (heap allocation overhead, Scheme/C round trips, etc.)  */
+
+SCM_DEFINE (scm_dereference_pointer, "dereference-pointer", 1, 0, 0,
+           (SCM pointer),
+           "Assuming @var{pointer} points to a memory region that\n"
+           "holds a pointer, return this pointer.")
+#define FUNC_NAME s_scm_dereference_pointer
+{
+  SCM_VALIDATE_POINTER (1, pointer);
 
-void
-scm_i_foreign_print (SCM foreign, SCM port, scm_print_state *pstate)
+  return scm_from_pointer (* (void **) SCM_POINTER_VALUE (pointer), NULL);
+}
+#undef FUNC_NAME
+
+SCM_DEFINE (scm_string_to_pointer, "string->pointer", 1, 1, 0,
+           (SCM string, SCM encoding),
+           "Return a foreign pointer to a nul-terminated copy of\n"
+           "@var{string} in the given @var{encoding}, defaulting to\n"
+            "the current locale encoding.  The C string is freed when\n"
+            "the returned foreign pointer becomes unreachable.\n\n"
+            "This is the Scheme equivalent of @code{scm_to_stringn}.")
+#define FUNC_NAME s_scm_string_to_pointer
 {
-  scm_puts ("#<foreign ", port);
-  switch (SCM_FOREIGN_TYPE (foreign))
+  SCM_VALIDATE_STRING (1, string);
+
+  /* XXX: Finalizers slow down libgc; they could be avoided if
+     `scm_to_string' & co. were able to use libgc-allocated memory.  */
+
+  if (SCM_UNBNDP (encoding))
+    return scm_from_pointer (scm_to_locale_string (string), free);
+  else
     {
-    case SCM_FOREIGN_TYPE_FLOAT:
-      scm_puts ("float ", port);
-      break;
-    case SCM_FOREIGN_TYPE_DOUBLE:
-      scm_puts ("double ", port);
-      break;
-    case SCM_FOREIGN_TYPE_UINT8:
-      scm_puts ("uint8 ", port);
-      break;
-    case SCM_FOREIGN_TYPE_INT8:
-      scm_puts ("int8 ", port);
-      break;
-    case SCM_FOREIGN_TYPE_UINT16:
-      scm_puts ("uint16 ", port);
-      break;
-    case SCM_FOREIGN_TYPE_INT16:
-      scm_puts ("int16 ", port);
-      break;
-    case SCM_FOREIGN_TYPE_UINT32:
-      scm_puts ("uint32 ", port);
-      break;
-    case SCM_FOREIGN_TYPE_INT32:
-      scm_puts ("int32 ", port);
-      break;
-    case SCM_FOREIGN_TYPE_UINT64:
-      scm_puts ("uint64 ", port);
-      break;
-    case SCM_FOREIGN_TYPE_INT64:
-      scm_puts ("int64 ", port);
-      break;
-    case SCM_FOREIGN_TYPE_VOID:
-      scm_puts ("pointer ", port);
-      break;
-    default:
-      scm_wrong_type_arg_msg ("%print-foreign", 1, foreign, "foreign");
+      char *enc;
+      SCM ret;
+      
+      SCM_VALIDATE_STRING (2, encoding);
+
+      enc = scm_to_locale_string (encoding);
+      scm_dynwind_begin (0);
+      scm_dynwind_free (enc);
+
+      ret = scm_from_pointer
+        (scm_to_stringn (string, NULL, enc,
+                         scm_i_default_port_conversion_handler ()),
+         free);
+
+      scm_dynwind_end ();
+
+      return ret;
+    }
+}
+#undef FUNC_NAME
+
+SCM_DEFINE (scm_pointer_to_string, "pointer->string", 1, 2, 0,
+           (SCM pointer, SCM length, SCM encoding),
+           "Return the string representing the C string pointed to by\n"
+            "@var{pointer}.  If @var{length} is omitted or @code{-1}, the\n"
+            "string is assumed to be nul-terminated.  Otherwise\n"
+            "@var{length} is the number of bytes in memory pointed to by\n"
+            "@var{pointer}.  The C string is assumed to be in the given\n"
+            "@var{encoding}, defaulting to the current locale encoding.\n\n"
+           "This is the Scheme equivalent of @code{scm_from_stringn}.")
+#define FUNC_NAME s_scm_pointer_to_string
+{
+  size_t len;
+
+  SCM_VALIDATE_POINTER (1, pointer);
+
+  if (SCM_UNBNDP (length)
+      || scm_is_true (scm_eqv_p (length, scm_from_int (-1))))
+    len = (size_t)-1;
+  else
+    len = scm_to_size_t (length);
+    
+  if (SCM_UNBNDP (encoding))
+    return scm_from_locale_stringn (SCM_POINTER_VALUE (pointer), len);
+  else
+    {
+      char *enc;
+      SCM ret;
+      
+      SCM_VALIDATE_STRING (3, encoding);
+
+      enc = scm_to_locale_string (encoding);
+      scm_dynwind_begin (0);
+      scm_dynwind_free (enc);
+
+      ret = scm_from_stringn (SCM_POINTER_VALUE (pointer), len, enc,
+                              scm_i_default_port_conversion_handler ());
+
+      scm_dynwind_end ();
+
+      return ret;
     }
-  scm_display (scm_foreign_ref (foreign), port);
-  scm_putc ('>', port);
 }
+#undef FUNC_NAME
 
 \f
 
@@ -447,35 +447,51 @@ SCM_DEFINE (scm_alignof, "alignof", 1, 0, 0, (SCM type),
       switch (SCM_I_INUM (type))
         {
         case SCM_FOREIGN_TYPE_FLOAT:
-          return scm_from_size_t (alignof (float));
+          return scm_from_size_t (alignof_type (float));
         case SCM_FOREIGN_TYPE_DOUBLE:
-          return scm_from_size_t (alignof (double));
+          return scm_from_size_t (alignof_type (double));
         case SCM_FOREIGN_TYPE_UINT8:
-          return scm_from_size_t (alignof (scm_t_uint8));
+          return scm_from_size_t (alignof_type (scm_t_uint8));
         case SCM_FOREIGN_TYPE_INT8:
-          return scm_from_size_t (alignof (scm_t_int8));
+          return scm_from_size_t (alignof_type (scm_t_int8));
         case SCM_FOREIGN_TYPE_UINT16:
-          return scm_from_size_t (alignof (scm_t_uint16));
+          return scm_from_size_t (alignof_type (scm_t_uint16));
         case SCM_FOREIGN_TYPE_INT16:
-          return scm_from_size_t (alignof (scm_t_int16));
+          return scm_from_size_t (alignof_type (scm_t_int16));
         case SCM_FOREIGN_TYPE_UINT32:
-          return scm_from_size_t (alignof (scm_t_uint32));
+          return scm_from_size_t (alignof_type (scm_t_uint32));
         case SCM_FOREIGN_TYPE_INT32:
-          return scm_from_size_t (alignof (scm_t_int32));
+          return scm_from_size_t (alignof_type (scm_t_int32));
         case SCM_FOREIGN_TYPE_UINT64:
-          return scm_from_size_t (alignof (scm_t_uint64));
+          return scm_from_size_t (alignof_type (scm_t_uint64));
         case SCM_FOREIGN_TYPE_INT64:
-          return scm_from_size_t (alignof (scm_t_int64));
+          return scm_from_size_t (alignof_type (scm_t_int64));
         default:
           scm_wrong_type_arg (FUNC_NAME, 1, type);
         }
     }
   else if (scm_is_eq (type, sym_asterisk))
     /* a pointer */
-    return scm_from_size_t (alignof (void*));
+    return scm_from_size_t (alignof_type (void*));
   else if (scm_is_pair (type))
-    /* a struct, yo */
-    return scm_alignof (scm_car (type));
+    {
+      /* TYPE is a structure.  Section 3-3 of the i386, x86_64, PowerPC,
+        and SPARC P.S. of the System V ABI all say: "Aggregates
+        (structures and arrays) and unions assume the alignment of
+        their most strictly aligned component."  */
+      size_t max;
+
+      for (max = 0; scm_is_pair (type); type = SCM_CDR (type))
+       {
+         size_t align;
+
+         align = scm_to_size_t (scm_alignof (SCM_CAR (type)));
+         if (align  > max)
+           max = align;
+       }
+
+      return scm_from_size_t (max);
+    }
   else
     scm_wrong_type_arg (FUNC_NAME, 1, type);
 }
@@ -617,7 +633,7 @@ fill_ffi_type (SCM type, ffi_type *ftype, ffi_type ***type_ptrs,
           *ftype = ffi_type_void;
           return;
         default:
-          scm_wrong_type_arg_msg ("make-foreign-function", 0, type,
+          scm_wrong_type_arg_msg ("pointer->procedure", 0, type,
                                   "foreign type");
         }
     }
@@ -650,27 +666,21 @@ fill_ffi_type (SCM type, ffi_type *ftype, ffi_type ***type_ptrs,
       ftype->elements[i] = NULL;
     }
 }
-    
-SCM_DEFINE (scm_make_foreign_function, "make-foreign-function", 3, 0, 0,
-            (SCM return_type, SCM func_ptr, SCM arg_types),
-            "Make a foreign function.\n\n"
-            "Given the foreign void pointer @var{func_ptr}, its argument and\n"
-            "return types @var{arg_types} and @var{return_type}, return a\n"
-            "procedure that will pass arguments to the foreign function\n"
-            "and return appropriate values.\n\n"
-            "@var{arg_types} should be a list of foreign types.\n"
-            "@code{return_type} should be a foreign type.")
-#define FUNC_NAME s_scm_make_foreign_function
+
+/* Return a "cif" (call interface) for the given RETURN_TYPE and
+   ARG_TYPES.  */
+static ffi_cif *
+make_cif (SCM return_type, SCM arg_types, const char *caller)
+#define FUNC_NAME caller
 {
-  SCM walk, scm_cif;
+  SCM walk;
   long i, nargs, n_structs, n_struct_elts;
   size_t cif_len;
   char *mem;
   ffi_cif *cif;
   ffi_type **type_ptrs;
   ffi_type *types;
-  
-  SCM_VALIDATE_FOREIGN_TYPED (2, func_ptr, VOID);
+
   nargs = scm_ilength (arg_types);
   SCM_ASSERT (nargs >= 0, arg_types, 3, FUNC_NAME);
   /* fixme: assert nargs < 1<<32 */
@@ -684,33 +694,33 @@ SCM_DEFINE (scm_make_foreign_function, "make-foreign-function", 3, 0, 0,
   for (walk = arg_types; scm_is_pair (walk); walk = scm_cdr (walk))
     if (!parse_ffi_type (scm_car (walk), 0, &n_structs, &n_struct_elts))
       scm_wrong_type_arg (FUNC_NAME, 3, scm_car (walk));
-  
+
   /* the memory: with space for the cif itself */
   cif_len = sizeof (ffi_cif);
 
   /* then ffi_type pointers: one for each arg, one for each struct
      element, and one for each struct (for null-termination) */
-  cif_len = (ROUND_UP (cif_len, alignof(void*))
-             + (nargs + n_structs + n_struct_elts)*sizeof(void*));
-  
+  cif_len = (ROUND_UP (cif_len, alignof_type (void *))
+            + (nargs + n_structs + n_struct_elts)*sizeof(void*));
+
   /* then the ffi_type structs themselves, one per arg and struct element, and
      one for the return val */
-  cif_len = (ROUND_UP (cif_len, alignof(ffi_type))
-             + (nargs + n_struct_elts + 1)*sizeof(ffi_type));
+  cif_len = (ROUND_UP (cif_len, alignof_type (ffi_type))
+            + (nargs + n_struct_elts + 1)*sizeof(ffi_type));
 
   mem = scm_gc_malloc_pointerless (cif_len, "foreign");
-  scm_cif = scm_take_foreign_pointer (SCM_FOREIGN_TYPE_VOID, mem,
-                                     cif_len, NULL);
+  /* ensure all the memory is initialized, even the holes */
+  memset (mem, 0, cif_len);
   cif = (ffi_cif *) mem;
 
   /* reuse cif_len to walk through the mem */
-  cif_len = ROUND_UP (sizeof (ffi_cif), alignof(void*));
+  cif_len = ROUND_UP (sizeof (ffi_cif), alignof_type (void *));
   type_ptrs = (ffi_type**)(mem + cif_len);
   cif_len = ROUND_UP (cif_len
-                      + (nargs + n_structs + n_struct_elts)*sizeof(void*),
-                      alignof(ffi_type));
+                     + (nargs + n_structs + n_struct_elts)*sizeof(void*),
+                     alignof_type (ffi_type));
   types = (ffi_type*)(mem + cif_len);
-  
+
   /* whew. now knit the pointers together. */
   cif->rtype = types++;
   fill_ffi_type (return_type, cif->rtype, &type_ptrs, &types);
@@ -727,12 +737,33 @@ SCM_DEFINE (scm_make_foreign_function, "make-foreign-function", 3, 0, 0,
   cif->nargs = nargs;
   cif->bytes = 0;
   cif->flags = 0;
-  
+
   if (FFI_OK != ffi_prep_cif (cif, FFI_DEFAULT_ABI, cif->nargs, cif->rtype,
-                              cif->arg_types))
-    scm_misc_error (FUNC_NAME, "ffi_prep_cif failed", SCM_EOL);
+                             cif->arg_types))
+    SCM_MISC_ERROR ("ffi_prep_cif failed", SCM_EOL);
 
-  return cif_to_procedure (scm_cif, func_ptr);
+  return cif;
+}
+#undef FUNC_NAME
+
+SCM_DEFINE (scm_pointer_to_procedure, "pointer->procedure", 3, 0, 0,
+            (SCM return_type, SCM func_ptr, SCM arg_types),
+            "Make a foreign function.\n\n"
+            "Given the foreign void pointer @var{func_ptr}, its argument and\n"
+            "return types @var{arg_types} and @var{return_type}, return a\n"
+            "procedure that will pass arguments to the foreign function\n"
+            "and return appropriate values.\n\n"
+            "@var{arg_types} should be a list of foreign types.\n"
+            "@code{return_type} should be a foreign type.")
+#define FUNC_NAME s_scm_pointer_to_procedure
+{
+  ffi_cif *cif;
+
+  SCM_VALIDATE_POINTER (2, func_ptr);
+
+  cif = make_cif (return_type, arg_types, FUNC_NAME);
+
+  return cif_to_procedure (scm_from_pointer (cif, NULL), func_ptr);
 }
 #undef FUNC_NAME
 
@@ -741,37 +772,40 @@ SCM_DEFINE (scm_make_foreign_function, "make-foreign-function", 3, 0, 0,
 /* Pre-generate trampolines for less than 10 arguments. */
 
 #ifdef WORDS_BIGENDIAN
-#define OBJCODE_HEADER 0, 0, 0, 8, 0, 0, 0, 40
-#define META_HEADER    0, 0, 0, 32, 0, 0, 0, 0
+#define OBJCODE_HEADER(M) M (0), M (0), M (0), M (8), M (0), M (0), M (0), M (40)
+#define META_HEADER(M)    M (0), M (0), M (0), M (32), M (0), M (0), M (0), M (0)
 #else
-#define OBJCODE_HEADER 8, 0, 0, 0, 40, 0, 0, 0
-#define META_HEADER    32, 0, 0, 0, 0, 0, 0, 0
+#define OBJCODE_HEADER(M) M (8), M (0), M (0), M (0), M (40), M (0), M (0), M (0)
+#define META_HEADER(M)    M (32), M (0), M (0), M (0), M (0), M (0), M (0), M (0)
 #endif
 
-#define CODE(nreq)                                                      \
-  OBJCODE_HEADER,                                                       \
-  /* 0 */ scm_op_assert_nargs_ee, 0, nreq, /* assert number of args */  \
-  /* 3 */ scm_op_object_ref, 0, /* push the pair with the cif and the function pointer */ \
-  /* 5 */ scm_op_foreign_call, nreq, /* and call (will return value as well) */ \
-  /* 7 */ scm_op_nop,                                                   \
-  /* 8 */ META (3, 7, nreq)
-
-#define META(start, end, nreq)                                         \
-  META_HEADER,                                                          \
-  /* 0 */ scm_op_make_eol, /* bindings */                               \
-  /* 1 */ scm_op_make_eol, /* sources */                                \
-  /* 2 */ scm_op_make_int8, start, scm_op_make_int8, end, /* arity: from ip N to ip N */ \
-  /* 6 */ scm_op_make_int8, nreq, /* the arity is N required args */    \
-  /* 8 */ scm_op_list, 0, 3, /* make a list of those 3 vals */         \
-  /* 11 */ scm_op_list, 0, 1, /* and the arities will be a list of that one list */ \
-  /* 14 */ scm_op_load_symbol, 0, 0, 4, 'n', 'a', 'm', 'e', /* `name' */ \
-  /* 22 */ scm_op_object_ref, 1, /* the name from the object table */   \
-  /* 24 */ scm_op_cons, /* make a pair for the properties */            \
-  /* 25 */ scm_op_list, 0, 4, /* pack bindings, sources, and arities into list */ \
-  /* 28 */ scm_op_return, /* and return */                              \
-  /* 29 */ scm_op_nop, scm_op_nop, scm_op_nop                           \
+#define GEN_CODE(M, nreq)                                               \
+  OBJCODE_HEADER (M),                                                   \
+  /* 0 */ M (scm_op_assert_nargs_ee), M (0), M (nreq), /* assert number of args */ \
+  /* 3 */ M (scm_op_object_ref), M (0), /* push the pair with the cif and the function pointer */ \
+  /* 5 */ M (scm_op_foreign_call), M (nreq), /* and call (will return value as well) */ \
+  /* 7 */ M (scm_op_nop),                                               \
+  /* 8 */ META (M, 3, 7, nreq)
+
+#define META(M, start, end, nreq)                                       \
+  META_HEADER (M),                                                      \
+  /* 0 */ M (scm_op_make_eol), /* bindings */                           \
+  /* 1 */ M (scm_op_make_eol), /* sources */                            \
+  /* 2 */ M (scm_op_make_int8), M (start), M (scm_op_make_int8), M (end), /* arity: from ip N to ip N */ \
+  /* 6 */ M (scm_op_make_int8), M (nreq), /* the arity is N required args */ \
+  /* 8 */ M (scm_op_list), M (0), M (3), /* make a list of those 3 vals */ \
+  /* 11 */ M (scm_op_list), M (0), M (1), /* and the arities will be a list of that one list */ \
+  /* 14 */ M (scm_op_load_symbol), M (0), M (0), M (4), M ('n'), M ('a'), M ('M'), M ('e'), /* `name' */ \
+  /* 22 */ M (scm_op_object_ref), M (1), /* the name from the object table */ \
+  /* 24 */ M (scm_op_cons), /* make a pair for the properties */        \
+  /* 25 */ M (scm_op_list), M (0), M (4), /* pack bindings, sources, and arities into list */ \
+  /* 28 */ M (scm_op_return), /* and return */                          \
+  /* 29 */ M (scm_op_nop), M (scm_op_nop), M (scm_op_nop)               \
   /* 32 */
 
+#define M_STATIC(x) (x)
+#define CODE(nreq) GEN_CODE (M_STATIC, nreq)
+
 static const struct
 {
   scm_t_uint64 dummy; /* ensure 8-byte alignment; perhaps there's a better way */
@@ -785,8 +819,28 @@ static const struct
   }
 };
 
-#undef CODE
+static SCM
+make_objcode_trampoline (unsigned int nargs)
+{
+  const int size = sizeof (struct scm_objcode) + 8
+    + sizeof (struct scm_objcode) + 32;
+  SCM bytecode = scm_c_make_bytevector (size);
+  scm_t_uint8 *bytes = (scm_t_uint8 *) SCM_BYTEVECTOR_CONTENTS (bytecode);
+  int i = 0;
+
+#define M_DYNAMIC(x) (bytes[i++] = (x))
+  GEN_CODE (M_DYNAMIC, nargs);
+#undef M_DYNAMIC
+
+  if (i != size)
+    scm_syserror ("make_objcode_trampoline");
+  return scm_bytecode_to_native_objcode (bytecode);
+}
+
+#undef GEN_CODE
 #undef META
+#undef M_STATIC
+#undef CODE
 #undef OBJCODE_HEADER
 #undef META_HEADER
 
@@ -803,7 +857,7 @@ static const struct
        (setq i (1+ i)))))
 */
 #define STATIC_OBJCODE_TAG                                      \
-  SCM_PACK (scm_tc7_objcode | (SCM_F_OBJCODE_IS_STATIC << 8))
+  SCM_PACK (SCM_MAKE_OBJCODE_TAG (SCM_OBJCODE_TYPE_STATIC, 0))
 
 static const struct
 {
@@ -849,17 +903,43 @@ static const SCM objcode_trampolines[10] = {
   SCM_PACK (objcode_cells.cells+18),
 };
 
+static SCM large_objcode_trampolines = SCM_UNDEFINED;
+static scm_i_pthread_mutex_t large_objcode_trampolines_mutex =
+  SCM_I_PTHREAD_MUTEX_INITIALIZER;
+
 static SCM
-cif_to_procedure (SCM cif, SCM func_ptr)
+get_objcode_trampoline (unsigned int nargs)
 {
-  unsigned nargs = SCM_FOREIGN_POINTER (cif, ffi_cif)->nargs;
-  SCM objcode, table, ret;
-  
+  SCM objcode;
+
   if (nargs < 10)
     objcode = objcode_trampolines[nargs];
+  else if (nargs < 128)
+    {
+      scm_i_scm_pthread_mutex_lock (&large_objcode_trampolines_mutex);
+      if (SCM_UNBNDP (large_objcode_trampolines))
+        large_objcode_trampolines = scm_c_make_vector (128, SCM_UNDEFINED);
+      objcode = scm_c_vector_ref (large_objcode_trampolines, nargs);
+      if (SCM_UNBNDP (objcode))
+        scm_c_vector_set_x (large_objcode_trampolines, nargs,
+                            objcode = make_objcode_trampoline (nargs));
+      scm_i_pthread_mutex_unlock (&large_objcode_trampolines_mutex);
+    }
   else
-    scm_misc_error ("make-foreign-function", "args >= 10 currently unimplemented",
+    scm_misc_error ("make-foreign-function", "args >= 128 currently unimplemented",
                     SCM_EOL);
+
+  return objcode;
+}
+
+static SCM
+cif_to_procedure (SCM cif, SCM func_ptr)
+{
+  ffi_cif *c_cif;
+  SCM objcode, table, ret;
+
+  c_cif = (ffi_cif *) SCM_POINTER_VALUE (cif);
+  objcode = get_objcode_trampoline (c_cif->nargs);
   
   table = scm_c_make_vector (2, SCM_UNDEFINED);
   SCM_SIMPLE_VECTOR_SET (table, 0, scm_cons (cif, func_ptr));
@@ -871,7 +951,8 @@ cif_to_procedure (SCM cif, SCM func_ptr)
 
 /* Set *LOC to the foreign representation of X with TYPE.  */
 static void
-unpack (const ffi_type *type, void *loc, SCM x)
+unpack (const ffi_type *type, void *loc, SCM x, int return_value_p)
+#define FUNC_NAME "scm_i_foreign_call"
 {
   switch (type->type)
     {
@@ -881,23 +962,45 @@ unpack (const ffi_type *type, void *loc, SCM x)
     case FFI_TYPE_DOUBLE:
       *(double *) loc = scm_to_double (x);
       break;
+
+    /* For integer return values smaller than `int', libffi expects the
+       result in an `ffi_arg'-long buffer.  */
+
     case FFI_TYPE_UINT8:
-      *(scm_t_uint8 *) loc = scm_to_uint8 (x);
+      if (return_value_p)
+       *(ffi_arg *) loc = scm_to_uint8 (x);
+      else
+       *(scm_t_uint8 *) loc = scm_to_uint8 (x);
       break;
     case FFI_TYPE_SINT8:
-      *(scm_t_int8 *) loc = scm_to_int8 (x);
+      if (return_value_p)
+       *(ffi_arg *) loc = scm_to_int8 (x);
+      else
+       *(scm_t_int8 *) loc = scm_to_int8 (x);
       break;
     case FFI_TYPE_UINT16:
-      *(scm_t_uint16 *) loc = scm_to_uint16 (x);
+      if (return_value_p)
+       *(ffi_arg *) loc = scm_to_uint16 (x);
+      else
+       *(scm_t_uint16 *) loc = scm_to_uint16 (x);
       break;
     case FFI_TYPE_SINT16:
-      *(scm_t_int16 *) loc = scm_to_int16 (x);
+      if (return_value_p)
+       *(ffi_arg *) loc = scm_to_int16 (x);
+      else
+       *(scm_t_int16 *) loc = scm_to_int16 (x);
       break;
     case FFI_TYPE_UINT32:
-      *(scm_t_uint32 *) loc = scm_to_uint32 (x);
+      if (return_value_p)
+       *(ffi_arg *) loc = scm_to_uint32 (x);
+      else
+       *(scm_t_uint32 *) loc = scm_to_uint32 (x);
       break;
     case FFI_TYPE_SINT32:
-      *(scm_t_int32 *) loc = scm_to_int32 (x);
+      if (return_value_p)
+       *(ffi_arg *) loc = scm_to_int32 (x);
+      else
+       *(scm_t_int32 *) loc = scm_to_int32 (x);
       break;
     case FFI_TYPE_UINT64:
       *(scm_t_uint64 *) loc = scm_to_uint64 (x);
@@ -906,26 +1009,28 @@ unpack (const ffi_type *type, void *loc, SCM x)
       *(scm_t_int64 *) loc = scm_to_int64 (x);
       break;
     case FFI_TYPE_STRUCT:
-      if (!SCM_FOREIGN_TYPED_P (x, VOID))
-       scm_wrong_type_arg_msg ("foreign-call", 0, x, "foreign void pointer");
-      if (SCM_FOREIGN_LEN (x) && SCM_FOREIGN_LEN (x) != type->size)
-       scm_wrong_type_arg_msg ("foreign-call", 0, x,
-                               "foreign void pointer of correct length");
-      memcpy (loc, SCM_FOREIGN_POINTER (x, void), type->size);
+      SCM_VALIDATE_POINTER (1, x);
+      memcpy (loc, SCM_POINTER_VALUE (x), type->size);
       break;
     case FFI_TYPE_POINTER:
-      if (!SCM_FOREIGN_TYPED_P (x, VOID))
-       scm_wrong_type_arg_msg ("foreign-call", 0, x, "foreign void pointer");
-      *(void **) loc = SCM_FOREIGN_POINTER (x, void);
+      SCM_VALIDATE_POINTER (1, x);
+      *(void **) loc = SCM_POINTER_VALUE (x);
+      break;
+    case FFI_TYPE_VOID:
+      /* Do nothing.  */
       break;
     default:
       abort ();
     }
 }
+#undef FUNC_NAME
 
-/* Return a Scheme representation of the foreign value at LOC of type TYPE.  */
+/* Return a Scheme representation of the foreign value at LOC of type
+   TYPE.  When RETURN_VALUE_P is true, LOC is assumed to point to a
+   return value buffer; otherwise LOC is assumed to point to an
+   argument buffer.  */
 static SCM
-pack (const ffi_type * type, const void *loc)
+pack (const ffi_type * type, const void *loc, int return_value_p)
 {
   switch (type->type)
     {
@@ -935,32 +1040,56 @@ pack (const ffi_type * type, const void *loc)
       return scm_from_double (*(float *) loc);
     case FFI_TYPE_DOUBLE:
       return scm_from_double (*(double *) loc);
+
+      /* For integer return values smaller than `int', libffi stores the
+        result in an `ffi_arg'-long buffer, of which only the
+        significant bits must be kept---hence the pair of casts below.
+        See <http://thread.gmane.org/gmane.comp.lib.ffi.general/406>
+        for details.  */
+
     case FFI_TYPE_UINT8:
-      return scm_from_uint8 (*(scm_t_uint8 *) loc);
+      if (return_value_p)
+       return scm_from_uint8 ((scm_t_uint8) *(ffi_arg *) loc);
+      else
+       return scm_from_uint8 (* (scm_t_uint8 *) loc);
     case FFI_TYPE_SINT8:
-      return scm_from_int8 (*(scm_t_int8 *) loc);
+      if (return_value_p)
+       return scm_from_int8 ((scm_t_int8) *(ffi_arg *) loc);
+      else
+       return scm_from_int8 (* (scm_t_int8 *) loc);
     case FFI_TYPE_UINT16:
-      return scm_from_uint16 (*(scm_t_uint16 *) loc);
+      if (return_value_p)
+       return scm_from_uint16 ((scm_t_uint16) *(ffi_arg *) loc);
+      else
+       return scm_from_uint16 (* (scm_t_uint16 *) loc);
     case FFI_TYPE_SINT16:
-      return scm_from_int16 (*(scm_t_int16 *) loc);
+      if (return_value_p)
+       return scm_from_int16 ((scm_t_int16) *(ffi_arg *) loc);
+      else
+       return scm_from_int16 (* (scm_t_int16 *) loc);
     case FFI_TYPE_UINT32:
-      return scm_from_uint32 (*(scm_t_uint32 *) loc);
+      if (return_value_p)
+       return scm_from_uint32 ((scm_t_uint32) *(ffi_arg *) loc);
+      else
+       return scm_from_uint32 (* (scm_t_uint32 *) loc);
     case FFI_TYPE_SINT32:
-      return scm_from_int32 (*(scm_t_int32 *) loc);
+      if (return_value_p)
+       return scm_from_int32 ((scm_t_int32) *(ffi_arg *) loc);
+      else
+       return scm_from_int32 (* (scm_t_int32 *) loc);
     case FFI_TYPE_UINT64:
       return scm_from_uint64 (*(scm_t_uint64 *) loc);
     case FFI_TYPE_SINT64:
       return scm_from_int64 (*(scm_t_int64 *) loc);
+
     case FFI_TYPE_STRUCT:
       {
        void *mem = scm_gc_malloc_pointerless (type->size, "foreign");
        memcpy (mem, loc, type->size);
-       return scm_take_foreign_pointer (SCM_FOREIGN_TYPE_VOID,
-                                        mem, type->size, NULL);
+       return scm_from_pointer (mem, NULL);
       }
     case FFI_TYPE_POINTER:
-      return scm_take_foreign_pointer (SCM_FOREIGN_TYPE_VOID,
-                                      *(void **) loc, 0, NULL);
+      return scm_from_pointer (*(void **) loc, NULL);
     default:
       abort ();
     }
@@ -981,8 +1110,8 @@ scm_i_foreign_call (SCM foreign, const SCM *argv)
   size_t arg_size;
   scm_t_ptrdiff off;
 
-  cif = SCM_FOREIGN_POINTER (SCM_CAR (foreign), ffi_cif);
-  func = SCM_FOREIGN_POINTER (SCM_CDR (foreign), void);
+  cif = SCM_POINTER_VALUE (SCM_CAR (foreign));
+  func = SCM_POINTER_VALUE (SCM_CDR (foreign));
 
   /* Argument pointers.  */
   args = alloca (sizeof (void *) * cif->nargs);
@@ -1007,7 +1136,7 @@ scm_i_foreign_call (SCM foreign, const SCM *argv)
       args[i] = (void *) ROUND_UP ((scm_t_uintptr) data + off,
                                   cif->arg_types[i]->alignment);
       assert ((scm_t_uintptr) args[i] % cif->arg_types[i]->alignment == 0);
-      unpack (cif->arg_types[i], args[i], argv[i]);
+      unpack (cif->arg_types[i], args[i], argv[i], 0);
     }
 
   /* Prepare space for the return value.  On some platforms, such as
@@ -1020,10 +1149,95 @@ scm_i_foreign_call (SCM foreign, const SCM *argv)
   /* off we go! */
   ffi_call (cif, func, rvalue, args);
 
-  return pack (cif->rtype, rvalue);
+  return pack (cif->rtype, rvalue, 1);
 }
 
 \f
+/* Function pointers aka. "callbacks" or "closures".  */
+
+#ifdef FFI_CLOSURES
+
+/* Trampoline to invoke a libffi closure that wraps a Scheme
+   procedure.  */
+static void
+invoke_closure (ffi_cif *cif, void *ret, void **args, void *data)
+{
+  size_t i;
+  SCM proc, *argv, result;
+
+  proc = PTR2SCM (data);
+
+  argv = alloca (cif->nargs * sizeof (*argv));
+
+  /* Pack ARGS to SCM values, setting ARGV pointers.  */
+  for (i = 0; i < cif->nargs; i++)
+    argv[i] = pack (cif->arg_types[i], args[i], 0);
+
+  result = scm_call_n (proc, argv, cif->nargs);
+
+  unpack (cif->rtype, ret, result, 1);
+}
+
+SCM_DEFINE (scm_procedure_to_pointer, "procedure->pointer", 3, 0, 0,
+           (SCM return_type, SCM proc, SCM arg_types),
+           "Return a pointer to a C function of type @var{return_type}\n"
+           "taking arguments of types @var{arg_types} (a list) and\n"
+           "behaving as a proxy to procedure @var{proc}.  Thus\n"
+           "@var{proc}'s arity, supported argument types, and return\n"
+           "type should match @var{return_type} and @var{arg_types}.\n")
+#define FUNC_NAME s_scm_procedure_to_pointer
+{
+  SCM cif_pointer, pointer;
+  ffi_cif *cif;
+  ffi_status err;
+  void *closure, *executable;
+
+  cif = make_cif (return_type, arg_types, FUNC_NAME);
+
+  closure = ffi_closure_alloc (sizeof (ffi_closure), &executable);
+  err = ffi_prep_closure_loc ((ffi_closure *) closure, cif,
+                             invoke_closure, SCM2PTR (proc),
+                             executable);
+  if (err != FFI_OK)
+    {
+      ffi_closure_free (closure);
+      SCM_MISC_ERROR ("`ffi_prep_closure_loc' failed", SCM_EOL);
+    }
+
+  /* CIF points to GC-managed memory and it should remain as long as
+     POINTER (see below) is live.  Wrap it in a Scheme pointer to then
+     hold a weak reference on it.  */
+  cif_pointer = scm_from_pointer (cif, NULL);
+
+  if (closure == executable)
+    {
+      pointer = scm_from_pointer (executable, ffi_closure_free);
+      register_weak_reference (pointer,
+                              scm_list_2 (proc, cif_pointer));
+    }
+  else
+    {
+      /* CLOSURE needs to be freed eventually.  However, since
+        `GC_all_interior_pointers' is disabled, we can't just register
+        a finalizer for CLOSURE.  Instead, we create a pointer object
+        for CLOSURE, with a finalizer, and register it as a weak
+        reference of POINTER.  */
+      SCM friend;
+
+      pointer = scm_from_pointer (executable, NULL);
+      friend = scm_from_pointer (closure, ffi_closure_free);
+
+      register_weak_reference (pointer,
+                              scm_list_3 (proc, cif_pointer, friend));
+    }
+
+  return pointer;
+}
+#undef FUNC_NAME
+
+#endif /* FFI_CLOSURES */
+
+\f
 
 static void
 scm_init_foreign (void)
@@ -1043,6 +1257,30 @@ scm_init_foreign (void)
   scm_define (sym_uint64, scm_from_uint8 (SCM_FOREIGN_TYPE_UINT64));
   scm_define (sym_int64, scm_from_uint8 (SCM_FOREIGN_TYPE_INT64));
 
+  scm_define (sym_short,
+#if SIZEOF_SHORT == 8
+             scm_from_uint8 (SCM_FOREIGN_TYPE_INT64)
+#elif SIZEOF_SHORT == 4
+             scm_from_uint8 (SCM_FOREIGN_TYPE_INT32)
+#elif SIZEOF_SHORT == 2
+             scm_from_uint8 (SCM_FOREIGN_TYPE_INT16)
+#else
+# error unsupported sizeof (short)
+#endif
+             );
+
+  scm_define (sym_unsigned_short,
+#if SIZEOF_SHORT == 8
+             scm_from_uint8 (SCM_FOREIGN_TYPE_UINT64)
+#elif SIZEOF_SHORT == 4
+             scm_from_uint8 (SCM_FOREIGN_TYPE_UINT32)
+#elif SIZEOF_SHORT == 2
+             scm_from_uint8 (SCM_FOREIGN_TYPE_UINT16)
+#else
+# error unsupported sizeof (short)
+#endif
+             );
+
   scm_define (sym_int,
 #if SIZEOF_INT == 8
              scm_from_uint8 (SCM_FOREIGN_TYPE_INT64)
@@ -1093,8 +1331,27 @@ scm_init_foreign (void)
 #endif
              );
 
-  null_pointer = scm_cell (scm_tc7_foreign | (SCM_FOREIGN_TYPE_VOID << 8UL),
-                           0);
+  scm_define (sym_ssize_t,
+#if SIZEOF_SIZE_T == 8
+             scm_from_uint8 (SCM_FOREIGN_TYPE_INT64)
+#elif SIZEOF_SIZE_T == 4
+             scm_from_uint8 (SCM_FOREIGN_TYPE_INT32)
+#else
+# error unsupported sizeof (ssize_t)
+#endif
+             );
+
+  scm_define (sym_ptrdiff_t,
+#if SCM_SIZEOF_SCM_T_PTRDIFF == 8
+             scm_from_uint8 (SCM_FOREIGN_TYPE_INT64)
+#elif SCM_SIZEOF_SCM_T_PTRDIFF == 4
+             scm_from_uint8 (SCM_FOREIGN_TYPE_INT32)
+#else
+# error unsupported sizeof (scm_t_ptrdiff)
+#endif
+             );
+
+  null_pointer = scm_cell (scm_tc7_pointer, 0);
   scm_define (sym_null, null_pointer);
 }
 
@@ -1105,7 +1362,7 @@ scm_register_foreign (void)
                             "scm_init_foreign",
                             (scm_t_extension_init_func)scm_init_foreign,
                             NULL);
-  foreign_weak_refs = scm_make_weak_key_hash_table (SCM_UNDEFINED);
+  pointer_weak_refs = scm_make_weak_key_hash_table (SCM_UNDEFINED);
 }
 
 /*