Next: , Previous: , Up: Alien Objects   [Contents][Index]


8.5 Alien Data Structure Example

Now that we have Alien types, operations and variables, we can manipulate foreign data structures. This C declaration can be translated into the following Alien type:

struct foo {
    int a;
    struct foo *b[100];
};

≡

(def-alien-type nil
  (struct foo
    (a int)
    (b (array (* (struct foo)) 100))))

With this definition, the following C expression can be translated in this way:

struct foo f;
f.b[7].a

≡ 

(with-alien ((f (struct foo)))
  (slot (deref (slot f 'b) 7) 'a)
  ;;
  ;; Do something with f...
  )

Or consider this example of an external C variable and some accesses:

struct c_struct {
        short x, y;
        char a, b;
        int z;
        c_struct *n;
};

extern struct c_struct *my_struct;

my_struct->x++;
my_struct->a = 5;
my_struct = my_struct->n;

which can be made be manipulated in Lisp like this:

(def-alien-type nil
  (struct c-struct
          (x short)
          (y short)
          (a char)
          (b char)
          (z int)
          (n (* c-struct))))

(def-alien-variable "my_struct" (* c-struct))

(incf (slot my-struct 'x))
(setf (slot my-struct 'a) 5)
(setq my-struct (slot my-struct 'n))

Next: Loading Unix Object Files, Previous: Alien Variables, Up: Alien Objects   [Contents][Index]