Skip to content
Prev 40168 / 63424 Next

cerr and cout not working calling c++ from R

Sean,

just to clarify - this is not about something "not working" or any leaks. cout/cerr do exactly what they are supposed to, it's just in most cases not what you want. The main reason is that R does not necessarily use stdin/stdout so cout/cerr may have nothing to do with the R console output. The effects of using cout/cerr vary by the actual setup in which you run R as I was explaining earlier. In the most complex setup (default for interactive R on OS X, actually) you have:

1) stdin/stdout/stderr - those are entirely independent of the R console
2) ReadConsole/WriteConsole - this is how R interacts with the console
3) C++ cin/cout/cerr - by default a buffered link to stdin/out/err

So as you see the reason for cout being strongly discouraged is simply because it has no relationship with R and produces no output in R itself. What makes things seemingly puzzling is that some UI implementations in R use stdin/out/err in Read/WriteConsole, so suddenly you are dealing with three independent streams and buffers (e.g., cout, WriteCondole and stdout all eventually ending in the same place but at different times). If your final output is a tty then they all get synchronized at the end into the same tty, but since each of them has a buffer, the result is random at the best.

Due to the interactions, you must be careful not to mess things up with any additional low-level stream manipulations. For example, the R.app GUI doesn't use stdout/err for console at all, since it is driven by text views instead, so it uses exclusively Read/WriteConsole (and so does the Windows GUI). However, it also monitors stdout/err for external output (e.g. from system()) and uses two separate pipes to merge that output into the console with different colors. So if you were to start to mess with the descriptors for stdout/err you could break that setup.

That said, if you want a solution for C++ you should simply write a stream or buffer that uses Rprintf/REprintf for output. I was assuming that others have done that before, but Dirk's response suggests that it is not as common. If you choose to do it, you may find this link helpful:
http://groups.google.com/group/comp.lang.c++/msg/1d941c0f26ea0d81

Cheers,
Simon
On May 7, 2011, at 12:42 AM, Sean Robert McGuffee wrote: