Is it possible to catch an error in C for Rf_eval R?

I need to catch a bug in Rf_evalc C. Is it possible?

Some selection function

SEXP foo(SEXP x, SEXP env) {
   SEXP res;
   PROTECT(res = Rf_eval(x, env));
   UNPROTECT(1); 
   return res;
}

I tried Rcpp_evalfrom Rcppand Rcpp11, but both of them do not work for my case, I need to call directly Rf_eval. Is it possible to catch an error directly in C? If so, how?

+4
source share
1 answer

use R_tryEval or R_tryEvalSilent in Rinternals.h

#include <Rdefines.h>

SEXP foo(SEXP fun, SEXP env)
{
    int err = 0;
    R_tryEval(fun, env, &err);
    if (err)
        Rprintf("error occurred\n");
    return R_NilValue;
}

with

> .Call("foo", quote(stop("oops")), .GlobalEnv)
Error: oops
error occurred
NULL

Here is a slightly more detailed example: getting the latest error

#include <Rdefines.h>

SEXP silent(SEXP fun, SEXP env, SEXP errmsg)
{
    int err = 0;
    SEXP result = PROTECT(R_tryEvalSilent(fun, env, &err));
    if (err) {
        SEXP msg = PROTECT(R_tryEvalSilent(errmsg, env, &err));
        if (!err)
            Rprintf("error occurred: %s",
                    CHAR(STRING_ELT(msg, 0)));
        else
            Rprintf("(unknown) error occurred");
        UNPROTECT(1);
        result = R_NilValue;
    }

    UNPROTECT(1);
    return result;
}

used as

.Call("silent", quote(stop("oops")), .GlobalEnv, quote(geterrmessage()))

, (, ) R, , , geterrmessage().

+5

All Articles