犰狳的 print() 方法和 cout 在从 Rcpp 调用时顺序不一致

Armadillo's print() method and cout are inconsistent in order when called from Rcpp

本文关键字:Rcpp 在从 调用 不一致 顺序 cout print 方法      更新时间:2023-10-16

最近,我一直在使用RcppArmadillo,但我注意到某些对象的打印顺序存在一些不一致。特别是,当使用coutprint()时。有时,print()会先打印,然后再打印cout;其他时候则相反。

我不明白为什么会发生这种情况。我想coutprint()是异步调用的,因此顺序不同,但为什么会这样呢?如何预防?

如果我有以下test_order.cpp文件

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;
using namespace arma;

// [[Rcpp::export]]
int test(int n){
cout << "Print 1n";
arma::mat X(n, n);
cout << "Print 2n";
X.print();
cout << "Print 3n";
return 1;
}

并像这样从 R 调用它

library(Rcpp)
sourceCpp("test_order.cpp")
test(3)

打印时得到不同的结果。三种不同的结果如下:

> test(3)
2.1220e-314            0  6.9531e-310Print 1
Print 2
2.3044e-314  6.9275e-310  6.9532e-310
2.1916e-314  2.1916e-314  2.2718e-314
Print 3
[1] 1
> test(3)
Print 1
Print 2
6.9531e-310  2.3044e-314  4.9407e-324
6.9532e-310  2.1916e-314  4.9407e-324
0  6.9275e-310  4.9407e-324
Print 3
[1] 1
> test(3)
6.9531e-310  2.3044e-314  4.9407e-324
6.9532e-310  2.1916e-314  4.9407e-324
0  6.9275e-310  4.9407e-324Print 1
Print 2
[1]Print 3
1

根据 Roland 和 Dirk的评论,以及 Dirk 的书和这篇 Rcpp 文章,解决方案是使用Rcout而不是coutprint()

根据德克的书:

因为 R 为我们的统计计算提供了"外壳", 程序需要将其(打印的(输出与使用 它自己的缓冲。

此外,CRAN 维护者标记包含std::cout的代码

。所以test_order.cpp文件应该是这样的:

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;
using namespace arma;

// [[Rcpp::export]]
int test(int n){
Rcout << "Print 1n";
arma::mat X(n, n);
Rcout << "Print 2n";
Rcout << X << "n";
Rcout << "Print 3n";
return 1;
}