Welcome to the CHICKEN Scheme pasting service

chicken-bind: suggestion for improved struct accessor functions added by klm` on Sun Mar 4 16:43:02 2012



;;; chicken-bind generates not-so-great helper functions for structures like this:

[klm@ksuo chicken]$ echo "typedef struct point {
>    float x, y;
> } point;" | chicken-bind - -o -

;;; GENERATED BY CHICKEN-BIND FROM -

(begin
  (define point-x
    (foreign-lambda* float (((c-pointer (struct "point")) s)) "return(s->x);"))
  (define point-y
    (foreign-lambda* float (((c-pointer (struct "point")) s)) "return(s->y);"))
  (define make-point
    (foreign-lambda*
      (c-pointer (struct "point"))
      ((float x) (float y))
      "struct point *tmp_ = (struct point *)C_malloc(sizeof(struct point));\ntmp_->x = x;\ntmp_->y = y;\nC_return(tmp_);")))

;;; I have a first-draft of a suggestion for alternative helper-functions:

;;; MANUALY CODED BY ME, could be generated from struct typedef above:

(define-record c-struct-point buffer)
(define-foreign-type c-struct-point scheme-object
  c-struct-point-buffer
  (lambda (returned-blob)
    (make-c-struct-point returned-blob)))

(define make-point (foreign-primitive c-struct-point ((float x) (float y))
#<<END
C_word ab [C_bytestowords(sizeof (struct point))];
struct point *_struct = (struct point*) C_data_pointer (ab);

_struct->x = x;
_struct->y = y;
ab [0] = C_BYTEVECTOR_TYPE | sizeof (struct point);
C_return (ab);
END
))

(define point-x (foreign-lambda* float ((c-struct-point point))
#<<END
C_return(((struct point*)C_data_pointer(point))->x);
END
))
(define point-y (foreign-lambda* float ((c-struct-point point))
#<<END
C_return(((struct point*)C_data_pointer(point))->y);
END
))

;; ----- 
;; testing with:
(define p (make-point 11 12))
(print "new struct is " p " and struct's blob is " (c-struct-point-buffer p))
(print "x of p is " (point-x p))
(print "y of p is " (point-y p))


;; outputs:
new struct is #<c-struct-point> and struct's blob is #${0000304100004041}
x of p is 11.0
y of p is 12.0

Your annotation:

Enter a new annotation:

Your nick:
The title of your paste:
Your paste (mandatory) :
What's the one-argument procedure to check if a list is empty?
Visually impaired? Let me spell it for you (wav file) download WAV