[gambit-list] c-structure accessor macro

Isaac Freeman memotype at gmail.com
Fri Sep 25 15:34:47 EDT 2009

In the spirit of wanting to learn not only the C FFI, but also gambit
macros, I decided to write a macro which generates accessors for C
structs. I decided to post it here for others to review, critique,
etc. Any feedback on style, methodology, etc is welcome. Also, I put
it on pastebin as well as in the e-mail body:

pastebin: http://paste.lisp.org/display/87730

(define-macro (define-c-struct name . members)
;(define (define-c-struct-test name members)

  ; -- internal utility functions

  (define (res-type-gen t)
    (let ((real-type (if (list? t)
                       (car t)
      (cond ((member real-type '(union type pointer nonnull-pointer
                                       function nonnull-function))
             "___result_voidstar = ")
            ((member real-type '(pointer nonnull-pointer function
             "___result_voidstar = (void*)")
            ((eq? real-type 'struct)
             "___result_voidstar = &")
              "___result = "))))

  (define (mem-acc-gen name-s mem type)
    `(define ,(string->symbol (string-append name-s "." mem))
       (c-lambda ((pointer ,name-s)) ,type
         ,(string-append (res-type-gen type) "___arg1->" mem ";"))))

  ; -- expansion

  (let* ((name-s (symbol->string name)))
       ,@(let loop ((ms members))
           (let* ((mem (symbol->string (caar ms)))
                  (type (cadar ms))
                  (res-type (res-type-gen type)))
               (mem-acc-gen name-s mem type)
               (if (null? (cdr ms))
                 (loop (cdr ms)))))))))

Isaac Freeman
memotype (at) gmail.com

"The diversity of mankind is a basic postulate of our knowledge of
human beings. But if mankind is diverse and individuated, then how can
anyone propose equality as an ideal? Every year, scholars hold
Conferences on Equality and call for greater equality, and no one
challenges the basic tenet. But what justification can equality find
in the nature of man? If each individual is unique, how else can he be
made 'equal' to others than by destroying most of what is human in him
and reducing human society to the mindless uniformity of the ant
heap?" --Murray N. Rothbard

More information about the Gambit-list mailing list