[plt-scheme] Linking Scheme- and C-variables

From: Eli Barzilay (eli at barzilay.org)
Date: Sat Nov 1 12:30:00 EST 2003

On Nov  1, Richard Cleis wrote:
>   For list-related administrative tasks:
>   http://list.cs.brown.edu/mailman/listinfo/plt-scheme
> I access c-doubles, for example, by making a closure-like primitive for 
> each variable:
> scheme_add_global( "access-the-double",
> 		       scheme_make_closed_prim_w_arity( AccessADouble,
>                                                      &theDouble,
>                                                      "access-the-double",
>                                                      0, 1), e);
> AccessADouble is written to return theDouble with 
> scheme_make_double(theDouble).  If a parameter is supplied, it is 
> validated then stored in theDouble first.
> Ie, (access-the-double 12.3) "sets" theDouble to 12.3.
> (access-the-double) "gets" 12.3 .

There is a related hack I once posted:

  (module fake-settable-vars mzscheme
    (provide defvar)
    (define-syntax (defvar stx)
      (syntax-case stx ()
        ((_ var val) (identifier? #'var)
         (with-syntax ((param (datum->syntax-object
                                (string-append (symbol->string (syntax-e #'var))
           #'(begin (define param (make-parameter val))
                    (define-syntax var
                       (lambda (stx)
                         (syntax-case stx (set!)
                           ((set! var1 val1) #'(param val1))
                           ((var . xs)       #'((param) . xs))
                           (var              #'(param))))))))))))

which uses parameters to fake variables that you can set! even outside
the module they were defined in.  You could use that on the Scheme
side so `the-double' translates to `(access-the-double)' and
`(set! the-double 12.3)' translates to `(access-the-double 12.3)'.  It
will look just like the above, except that you won't need to use
`make-parameter'.  Maybe something like (untested code):

  (module fake-accessible-vars mzscheme
    (provide def-access-var)
    (define-syntax def-access-var
      (syntax-rules stx ()
        ((def-access-var var accessor)
         (define-syntax var
            (lambda (stx)
              (syntax-case stx (set!)
                ((set! var val) #'(accessor val))
                ((var . xs)     #'((accessor) . xs))
                (var            #'(accessor))))))))))

> I veered away from the set! route since I don't like the idea of 
> parallel universes of variables when the two languages are so 
> different.  What happens if a c-double shadows a scheme variable that 
> is set with (sqrt -1) ?

This definitely seems like a sane approach...

          ((lambda (x) (x x)) (lambda (x) (x x)))          Eli Barzilay:
                  http://www.barzilay.org/                 Maze is Life!

Posted on the users mailing list.