chicken-users
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Chicken-users] Getting C file handle from port?


From: Thomas Chust
Subject: Re: [Chicken-users] Getting C file handle from port?
Date: Sat, 20 Mar 2010 15:55:26 +0100

2010/3/20 Jeronimo Pellegrini <address@hidden>:
> [...]
> Suppose I have an open port:
>
> (let ((in (open-input-file "whatever")))
>  ...
>  (let ((x (read in)))
>    ...))
>
> I'd like to switch from using Chicken's read implementation to
> something I'd write in C (using the FFI). But I didn't find in
> the documentation anything that would allow me to turn a port
> into a C file handle.
> [...]

Hello Jeronimo,

internally CHICKEN uses the C stdio facilities for regular file ports
anyway, so this is well possible: A regular file port is a block
object containing the FILE * in its first slot and a set of port
operation procedures specific for regular file ports in its third
slot. You should first check for the correct type of the port, then
extract the file pointer and use it.

Using the FFI, something like this should do the trick:

  (require-library
   lolevel)

  (module fputs
    (stream-port? fputs)
    (import scheme chicken foreign lolevel)

  (foreign-declare
   "#include <stdio.h>\n")

  (define (stream-port? v)
    (and (port? v)
         (eq? (block-ref v 2) ##sys#stream-port-class)))

  (define (fputs data #!optional [port (current-output-port)])
    (ensure stream-port? port)
    ((foreign-lambda* void ([c-string data] [scheme-object port])
       "fputs(data, (FILE *)C_block_item(port, 0));\n")
     data port))

  )

Ciao,
Thomas


-- 
When C++ is your hammer, every problem looks like your thumb.




reply via email to

[Prev in Thread] Current Thread [Next in Thread]