[R] Evaluating expressions from within C code

ripley@stats.ox.ac.uk ripley at stats.ox.ac.uk
Mon Jan 13 11:15:03 CET 2003


You need to define x as a variable known to R in environment rho.
Hint: look at install() in R-exts.texi.  I guess you want

defineVar(install("x"), x, rho)

but please read about the alternatives.


On Mon, 13 Jan 2003, Timur Elzhov wrote:

> Dear R experts!
>
> I want to evaluate expressions from within C code. For instance,
> I want this code:
>
>     /* ============ -- C code -- ============== */
>
>     #include <R.h>
>     #include <Rinternals.h>
>
>     SEXP foo(SEXP expr, SEXP rho)
>     {
>         SEXP x;
>
>         PROTECT(x = allocVector(REALSXP, 1));
>         REAL(x)[0] = 1;
>
>         UNPROTECT(1);
>
>         return eval(expr, rho);

I'd watch where you unprotect here.  You have unprotected x before
attempting to use it.

>     }
>     /* ======================================== */
>
>
>     .Call("foo", quote(x + 1), new.env())
>
> to return 1 + 1 == 2. But it certainly does not work:
>
>     .Call("foo", quote(x + 1), new.env())
>     Error: Object "x" not found
>
> and if I define x in R, it works:
>
>     x <- 1
>     .Call("foo", quote(x + 1), new.env())
>     [1] 2
>
> So, is there a way to solve my problem, namely to
> find and evaluate expressions that appears in C code?
>
> Thank you very much.
>
> --
> WBR,
> Timur.
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> http://www.stat.math.ethz.ch/mailman/listinfo/r-help
>

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list