[Rd] cerr and cout not working calling c++ from R

Dirk Eddelbuettel edd at debian.org
Fri May 6 20:41:49 CEST 2011


On 6 May 2011 at 14:21, Sean Robert McGuffee wrote:
| Hi,
| 
| Sorry, I just tried posting this but I had it in the wrong format of text,
| so this is a cleared format repost:
| 
| I¹m trying to call some of my c++ code from R and seem to be having an issue
| with streams, although that¹s just one obvious sign of something different
| in performance between calling the same function from main in c++ vs.
| calling the same function from R. I¹m not getting any signs of errors from
| R, but the behavior is different somehow and in a way that breaks my
| algorithms. In both cases of launching a function from c++ or R, I redirect
| cout to a file using a streambuf. In particular, I can see progress stop
| when launching from R at a point when cout gets truncated when starting to
| write out iterator values in a std::vector<string>. Then, I find no way to
| write anything else to cout. When I write those values to Rprintf, they are
| there and they are as expected. I¹ve tried setting
| ios_base::sync_with_stdio(false) in case R is messing with stdout and stderr
| somehow, but that made no difference. I¹m not quite sure how R uses those C
| FILE* streams. Anyway, I am wondering if anyone has a hunch as to what might
| be going on. At this point I don¹t know if it might be an issue with R not
| completely handling c++ from a library or if it is an issue with cout in
| particular or if there is something else I¹m missing. Please let me know if
| you have any suggestions for me.

Doug Bates sometimes remarks that, once all other alternatives are exhausted,
one could consider reading the manual. And indeed, 'Writing R Extensions' has
this to say:

   5.6 Interfacing C++ code
   ========================

   [...]

      Using C++ iostreams, as in this example, is best avoided.  There is
   no guarantee that the output will appear in the R console, and indeed it
   will not on the R for Windows console.  Use R code or the C entry points
   (*note Printing::) for all I/O if at all possible.
   
In a nutshell, R 'owns' your console. That is part of the Faustian bargain.

Dirk

-- 
Gauss once played himself in a zero-sum game and won $50.
                      -- #11 at http://www.gaussfacts.com



More information about the R-devel mailing list