[plt-scheme] String as output parameter of FFI call to W32 API GetLogicalDriveStringsW?

From: Andrea Girotto (andrea.girotto at gmail.com)
Date: Tue Feb 2 04:04:06 EST 2010

On Tue, Feb 2, 2010 at 3:56 AM, Matthew Flatt <mflatt at cs.utah.edu> wrote:
[...]
> I'd wrap the function like this:
>
>  (define get-logical-drive-strings
>   (let ([prim
>          (get-ffi-obj "GetLogicalDriveStringsW" kernel32
>                       (_fun #:abi 'stdcall
>                             _uint32
>                             _bytes
>                             -> _uint32))])
>     (lambda ()
>       (let* ([len (prim 0 #f)]
>              ;; Allocate buffer of needed size:
>              [bstr (make-bytes (* (add1 len) 2))])
>         (prim len bstr)
>         ;; Pull out the strings:
>         (let loop ([offset 0])
>           (let ([s (cast (ptr-add bstr offset) _pointer _string/utf-16)])
>             (if (equal? s "") ;; empty string terminates the sequence
>                 null
>                 (cons s (loop (+ offset
>                                  (* 2 (add1 (string-length s)))))))))))))
>
> The use of `cast' is an easy (if a bit hack-ish) way to convert the raw
> UTF-16 bytes into a Scheme string.
>
Right, it works wonderfully.
Now I understand: to use a string as an output parameter I need to
revert back to byte buffers and manually cast into scheme strings.

Thank you.
Best regards,
Andrew


Posted on the users mailing list.