[plt-scheme] Redirect standard output from ffi C dll to DrScheme Interactions window
Eli Barzilay wrote:
> On Feb 22, Rodrigo Correia wrote:
>> [...]
>> My question is, how can i redirect the C standard output to DrScheme
>> interactions window?
>
> You can't. If you really want to get close, you could fire up
> mzscheme as a subprocess, which would capture it's IO as usual.
Hello,
of course you *can* do that, it is just neither very portable nor
comfortable ;-)
You can find a module attached to this message that should work on POSIX
compliant systems and redirects any output that goes to file descriptor
1 into Scheme's (current-output-port) or any other specified output
port. Start DrScheme or MrEd from a terminal window in the same
directory as the module, then try the following in the interactions window:
(require "stdout.ss")
(puts "Hello Terminal!") ;; Output should go to terminal
(redirect-stdout!)
(puts "Hello GUI!") ;; Output should go to the GUI window
The code works by creating a pipe, duplicating the pipe's output side
over the file descriptor 1, creating a Scheme input port from the pipe's
input side and spawning a Scheme thread that copies data from the port
connected to the pipe into the current output port.
Keep in mind that the operating system buffers associated with pipes are
finite, so if your C code spews large amounts of data onto file
descriptor 1, make sure that the Scheme thread copying that data into
the target Scheme output port gets a chance to run frequently. If the
pipe's buffers get full during a write operation from C, your program
will just block infinitely.
If you only want to redirect stdout from the C standard library but
leave file descriptor 1 alone, create a named pipe instead, use freopen
from C to replace stdout with the pipe's output side and open-input-file
from Scheme to connect to the pipe's input side then copy from the
resulting port to the target port of your choice as in my example code.
This can even be done without using the FFI.
If you are not in a unixoid environment, I guess you're out of luck --
but that's true anyway independent of the output redirection problem ;-)
Ciao,
Thomas
--
When C++ is your hammer, every problem looks like your thumb.
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: stdout.ss
URL: <http://lists.racket-lang.org/users/archive/attachments/20100223/e971f6b5/attachment.ksh>