[plt-scheme] cffi questions

From: Matthew Flatt (mflatt at cs.utah.edu)
Date: Thu Jan 1 16:39:07 EST 2004

At Thu, 1 Jan 2004 12:10:04 -0500 (EST), "David A. Herman" wrote:
> 1. Is there any way a c-lambda function can access a regular Scheme
> function from within the same module? For example:
> (module my-lib mzscheme
>   (require (lib "cffi.ss" "compiler"))
>   (define (local-func a b) (+ a b)
>   (define c-func
>     (c-lambda (int) int
>       "Scheme_Object *lf;
>        Scheme_Object *args[2];
>        lf = /* somehow look up local-func in this module */
>        args[0] = scheme_make_integer(42);
>        args[1] = ___arg1;
>        ___result = scheme_apply(lf, 2, args);"))
>   (provide local-func c-func))

Probably the simplest solution is to pass it in as an argument to the C
function. In other words, add a scheme-object argument to c-func, and
instead of exporting c-func, export a wrapper that calls c-func with
local-func plus the rest of the arguments.

> 2. Is it safe to access the variables `argc' and `argv' from within a
> c-lambda function? They don't seem to be documented, but I've discovered
> empirically that those are their names. These variables are needed as
> parameters to e.g. the scheme_wrong_type function.

It's safe, and from now on, those bidings will be guaranteed and

> 3. Is it a bad idea to make a C header file to separate out struct
> definitions, #define's, and the like? I felt like they were cluttering the
> Scheme file, but the only way I could figure out to include the header was
> to add its directory to the search path at the mzc command line (which is
> bad because the -I flag isn't the same for all C compilers).

Would it help to have a `c-include' macro that reads the content of a
file and produces a `c-declare' form? That way, MzScheme can figure out
the path relative to the `c-include' use, instead of having the C
compiler deal with it.

I've added `c-include' to cffi. It's implemented as follows, but with
slightly more error checking.

  (require-for-syntax (lib "path-spec.ss" "syntax"))
  (define-syntax (c-include stx)
    (syntax-case stx () 
      [(_ path)
       (let ([pathname (resolve-path-spec #'path #'path stx #'build-path)])
         (let ([str
                (with-input-from-file pathname
                    (lambda () (read-string (file-size pathname))))])
           (quasisyntax/loc stx (c-declare #,str))))]))


Posted on the users mailing list.