[Rcpp-devel] How to handle std::cout/std::cerr in shared libraries

Watal M. Iwasaki heavy.watal at gmail.com
Fri Oct 26 18:26:31 CEST 2018


Dear Dirk,

Sorry for my poor explanation. I have read
`inst/include/Rcpp/iostream/Rstreambuf.h` and think I understand the role
of Rcpp::Rcout, but failed to explain my point. By "users [...] can just
stick to std::cout", I did not mean allowing users to write to stdout via
std::cout. It is about changing the destination of std::cout from stdout to
R's i/o. The following code hopefully explains better:

```
// [[Rcpp::export]]
void example_function() {
    // Normal state
    std::cout   << "to stdout; BAD\n";
    Rcpp::Rcout << "to R's i/o\n";

    // Ideal state
    std::streambuf* stdoutbuf = std::cout.rdbuf(Rcpp::Rcout.rdbuf());
    std::cout   << "to R's i/o via Rcpp::Rcout.buf; GOOD\n"
    Rcpp::Rcout << "to R's i/o\n";

    // Restore original state
    std::cout.rdbuf(stdoutbuf);
    std::cout   << "to stdout; BAD\n";
    Rcpp::Rcout << "to R's i/o\n";
}
```

In other words, we don't have to replace std::cout with Rcpp::Rcout. We
only have to change its buffer.

Thanks,
Watal

On Sat, Oct 27, 2018 at 12:09 AM Dirk Eddelbuettel <edd at debian.org> wrote:

>
> Hi Watal,
>
> On 26 October 2018 at 23:36, Watal M. Iwasaki wrote:
> | Is it possible for Rcpp to do some pre-execution hook before user code?
> For
> | example, if Rcpp system can hijack the std::cout buffer by executing
> | `std::cout.rdbuf(Rcpp::Rcout.rdbuf())` automatically, then Rcpp users
> (and
> | external libraries) no longer have to care about Rcout, and can just
> stick
> | to std::cout.
>
> Sorry, but we need the opposite (which is what Rcpp::Rcout does): we need
> to
> get what _would otherwise go to std::cout_ and feed it to Rcpp::Rcout which
> then hands it to R's buffered i/o.  That is the whole underlying reason --
> see the as always very detailed "Writing R Extensions" manual for a bit
> more.
>
> Automating that (ie replacing std::cout by Rcpp::Rcout) is what is needed.
>
> Dirk
>
>
> --
> http://dirk.eddelbuettel.com | @eddelbuettel | edd at debian.org
>


-- 
Watal M. Iwasaki / 岩嵜 航
SOKENDAI, The Graduate University for Advanced Studies,
Hayama, Kanagawa 240-0193, Japan
+81-46-858-1576
https://heavywatal.github.io/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20181027/b4f57672/attachment.html>


More information about the Rcpp-devel mailing list