如何在Rcpp中安全地生成R警告

时间:2014-07-03 15:25:26

标签: r warnings rcpp longjmp

我们知道在Rcpp中应该避免调用Rf_error(),因为它涉及堆栈上的C ++析构函数的longjmp。这就是为什么我们宁愿在Rcpp代码中抛出C ++异常(如throw Rcpp::exception("...")或通过stop("...")函数)。

但是,R警告也可能导致对Rf_error()的调用(此行为取决于warn选项)。因此,拨打Rf_warning()也存在风险。

Rcpp::sourceCpp(code = '

   #include <Rcpp.h>
   using namespace Rcpp;

   class Test {
      public:
         Test() { Rcout << "start\\n"; }
         ~Test() { Rcout << "end\\n"; }
   };

   // [[Rcpp::export]]
   void test() {
      Test t;
      Rf_warning("test");
   }
')

options(warn=10)
test()
## start
## Error in test() : (converted from warning) test

我们发现析构函数没有被调用(没有&#34;结束&#34;消息)。

如何以C ++ - 析构函数友好的方式生成R警告?

2 个答案:

答案 0 :(得分:11)

我提出的解决方案之一涉及从Rcpp调用R的warning函数:

// [[Rcpp::export]]
void test() {
   Test t;
   Function warning("warning");
   warning("test"); // here R errors are caught and transformed to C++ exceptions
}

如果warn>2

,则会给出正确的行为
start
end
Error in eval(expr, envir, enclos) : (converted from warning) test

我想知道是否有人对此有更好的了解。

答案 1 :(得分:7)

我建议使用stop()(这是try/catch的包装)代替:

稍微修改您的代码:

#include <Rcpp.h>
using namespace Rcpp;

class Test {
public:
    Test() { Rcout << "start\n"; }
    ~Test() { Rcout << "end\n"; }
};

// [[Rcpp::export]]
void test() {
    Test t;
    Rf_warning("test");
}

// [[Rcpp::export]]
void test2() {
    Test t;
    stop("test2");
}

/*** R
options(warn=10)
#test()
test2()
*/

我得到了理想的行为:

R> sourceCpp("/tmp/throw.cpp")

R> options(warn=10)

R> #test()
R> test2()
start
end
Error in eval(expr, envir, enclos) (from srcConn#3) : test2
R> 

longjmp问题已为人所知,但你不能通过避免我们展开对象的机制来获胜。