I'm being greedy here ... how can I modify this code so that if I have:

(c-define-type Foo:Bar "FooBar")

(define-array-allocator-and-accessors Foo:Bar)

will result in using "FooBar" in the generated *.c file rather than Foo:Bar



On Sat, Feb 14, 2009 at 9:32 PM, Marc Feeley <feeley@iro.umontreal.ca> wrote:

On 15-Feb-09, at 12:29 AM, lowly coder wrote:

... wow ... thanks!

On Sat, Feb 14, 2009 at 9:14 PM, Marc Feeley <feeley@iro.umontreal.ca> wrote:

On 14-Feb-09, at 11:58 PM, lowly coder wrote:

question 1:

Is it possible to write gambit code to produce the equiv of:
int foo[200]; ?

the current best I have in mind is:
(let ((foo (malloc (* 200 8)))) ... )

Here is another, more generic, approach which uses a macro to generate the various functions:


(c-declare #<<end-of-c-declare

#include <stdlib.h>

end-of-c-declare
)

(define-macro (define-array-allocator-and-accessors type)

 (define (sym . syms)
   (string->symbol (apply string-append
                          (map symbol->string syms))))

 (let ((type-str (symbol->string type)))
   `(begin

      (define ,(sym 'alloc- type '-array)
        (c-lambda (int) (pointer ,type)
                  ,(string-append
                    "___result_voidstar = malloc( ___arg1 * sizeof("
                    type-str
                    ") );")))

      (define ,(sym 'free- type '-array)
        (c-lambda ((pointer ,type)) void
                  "free( ___arg1 );"))

      (define ,(sym type '-array-ref)
        (c-lambda ((pointer ,type) int) ,type
                  "___result = ___arg1[___arg2];"))

      (define ,(sym type '-array-set!)
        (c-lambda ((pointer ,type) int ,type) void

                  "___arg1[___arg2] = ___arg3;")))))

;; test it:

(define-array-allocator-and-accessors int)
(define-array-allocator-and-accessors double)

(define a (alloc-int-array 5))
(define b (alloc-double-array 10))


(int-array-set! a 1 111)
(int-array-set! a 2 222)
(pp (+ (int-array-ref a 1) (int-array-ref a 2))) ;; 333

(double-array-set! b 1 1.5)
(double-array-set! b 2 2.0)
(pp (+ (double-array-ref b 1) (double-array-ref b 2))) ;; 3.5

(free-int-array a)
(free-double-array b)