[plt-scheme] FFI, argc and argv

From: Eli Barzilay (eli at barzilay.org)
Date: Sun May 6 10:11:07 EDT 2007

On May  6, Paulo J. Matos wrote:
> Hello all,
> If I have a function in C that receives int argc, and char **argv,
> what's the best way to warp it up?
> Two issues come to my mind:
> - command-line-arguments do not provide, afaik, argv[0].

No, that's the reason for `-C'.

> - I would have to convert the vector (command-line-arguments) to a
> cvector and pass it up to the function. Something like (list->cvector
> (vector->list (command-line-arguments)) _string) however I'm not sure
> if this is the best way to handle things.
> Any suggestions?

What you want to do is simple, and it works:

  (define main
    (get-ffi-obj "main" "x.so" (_fun _int _cvector -> _void)))
  (main 3 (list->cvector '("a" "b" "c") _string))

But the `_list' type does just that:

  (define main
    (get-ffi-obj "main" "x.so" (_fun _int (_list i _string) -> _void)))
  (main 3 '("d" "e" "f"))

And you can also specify the argument list, so the Scheme interface
consumes a single argument and passes it in two places to the C side:

  (define main
    (get-ffi-obj "main" "x.so"
      (_fun (l) :: (_int = (length l)) ((_list i _string) = l) -> _void)))
  (main '("g" "h" "i"))

You don't even need to convert the vector to a list because _vector
does that:

  (define main
    (get-ffi-obj "main" "x.so"
      (_fun (v) :: (_int = (vector-length v)) ((_vector i _string) = v)
            -> _void)))
  (main '#("j" "k" "l"))

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

Posted on the users mailing list.