[R] Calling R function from within C code

Timur Elzhov Timur.Elzhov at jinr.ru
Thu Jan 16 19:50:03 CET 2003


On Thu, Jan 16, 2003 at 03:22:42PM +0000, ripley at stats.ox.ac.uk wrote:
>>    I'd like to call R function from within C code.
>>    I looked through the 'R exts' manual, found examples with
>>    lang2(R_fcall, list), and tried it, but it seemed to create
>>    the call, which can accept only a single argument of 'list'
>>    type, when I need to create the call of R functions with
>>    arbitrary numbers of arguments.
>>
>>    How can I do it?
> That way.  It's a pairlist of arguments.  As that manual says
> 
> Function @code{lang2} creates an executable `list' of two elements, but
> this will only be clear to those with a knowledge of a LISP-like
> language.
> 
> There are examples in optim.c and deriv.c.

Excuse me that I'm so stupid :)
I couldn't find direct instructions how should I use lang2..

This is my C code. I create an empty pairlist of length 2,
and then attach it to R_fcall:

/* ================= R-test.c ================= */

SEXP foo(SEXP fn, SEXP elmt1, SEXP elmt2, SEXP rho)
{
    SEXP R_fcall, args, ans;

    PROTECT( R_fcall = lang2(fn, R_NilValue)   );
    PROTECT( args    = allocVector(LISTSXP, 2) );

    SETCAR ( args, elmt1 );
    SETCADR( args, elmt2 );

    SETCADR( R_fcall, args );

    PROTECT( ans = eval(R_fcall, rho) );


    UNPROTECT(3);

    return ans;

}

/* ============================================ */

Then, I create a simple R function f(x, y) and call it:

  f <- function(x, y) match.call()

  .Call("foo", rnorm, 1, 2, new.env())
    function (x, y) 
    match.call()(x = list(1, 2))

So, the only the _first_ `x' argument is evaluated to _list_..
I'm sorry, where I'm wrong?!

Thank you!


--
WBR,
Timur.




More information about the R-help mailing list