Subject: [clisp-list] FFI:C-POINTER and C null pointers

From: Aurelio Bignoli <[email-masked]>
Date: Tue Jul 16 13:52:03 2002

Let's suppose I have to interface the following C code:

--*-- hairy.h 
typedef struct 
{
  /* A lot of fields, many of them function pointers, used only
     by C functions. */
}
REALLY_HAIRY_STRUCT;

REALLY_HAIRY_STRUCT * make_really_hairy_struct (int how_many_hair);

int do_something (REALLY_HAIRY_STRUCT *h);
--*-- 

--*-- hairy.c
REALLY_HAIRY_STRUCT *
make_really_hairy_struct (int how_many_hair)
{
  REALLY_HAIRY_STRUCT *result = malloc (sizeof (REALLY_HAIRY_STRUCT));
  /* Structure initializaton. */
  return result;
}
int
do_something (REALLY_HAIRY_STRUCT *s)
{
  printf ("do_something: %p\n", s);
  if (s != 0)
    {
      printf ("Freeing %p...\n", s);
      free (s);
    }
  return 0;
}
--*--

To solve the problem I wrote the following lisp file:

--*-- hairy.lisp
(use-package :ffi)

(def-c-type REALLY-HAIRY-STRUCT c-pointer)

(def-c-call-out make-really-hairy-struct
  (:arguments (how-many-hair int :in))
  (:name "make_really_hairy_struct")
  (:return-type REALLY-HAIRY-STRUCT))

(def-c-call-out do-something
  (:name "do_something")
  (:arguments (h REALLY-HAIRY-STRUCT :in))
  (:return-type int))
--*--

I compiled it, linked, made a module etc. It works fine:

[6]> (make-really-hairy-struct 1200)
#<FOREIGN-ADDRESS #x0828F238>
[7]> (do-something *)
do_something: 0x828f238
Freeing 0x828f238...
0

The problem is: how can I call do_something from CLISP passing it a
null pointer as argument? NIL or 0 are not automatically converted
into FFI:C-POINTER and AFAIK there isn't any way to create a foreign
object at runtime.

I devised the following workaround: I defined an external C variable
in hairy.c:

   void * c_null = 0;

and a c-var in hairy.lisp:

   (def-c-var NULL (:name "c_null") (:type c-pointer))

so I can call do-something with NULL as argument:

[8]> (do-something NULL)
do_something: (nil)
0

Is there any better solution? Or is such a null foreign pointer
already defined somewhere? 

Ciao,
Aurelio

---

From: Sam Steingold <[email-masked]>
Date: Tue Jul 16 14:30:03 2002

> * In message <[email-masked]>
> * On the subject of "[clisp-list] FFI:C-POINTER and C null pointers"
> * Sent on Tue, 16 Jul 2002 22:42:10 +0200
> * Honorable Aurelio Bignoli <[email-masked]> writes:
>

does
        (h (c-ptr-null REALLY-HAIRY-STRUCT) :in)
help?
-- 
Sam Steingold (http://www.podval.org/~sds) running RedHat7.2 GNU/Linux
<http://www.camera.org> <http://www.iris.org.il> <http://www.memri.org/>
<http://www.mideasttruth.com/> <http://www.palestine-central.com/links.html>
Never succeed from the first try - if you do, nobody will think it was hard.