[Rd] existence of easy example of .Call??

Douglas Bates bates at stat.wisc.edu
Fri Jul 30 16:20:15 CEST 2004

Freja.Vamborg at astrazeneca.com wrote:
> Dear R-develers,
> I have been seraching in vain for an example of source-code, using .Call, to
> call an R-function from within C.
> Am also wondering i this .Call command works for all functions, say if I
> write a function analyse<-function()
> within my R functoin, can this function be called by the c-code called later
> in the same function.
> Eg, 
> my.function<-function(){
> ...
> analyse<-function() {}
> result<-.Call("My.c.code",...)
> }
> I then want My.c.code to call, analyse..
> I have read the R-extension manual, but am just wondernig if anyone has
> another example of use of .Call, which may be more clear to a beginning
> user.

This is not as simple as it may seem it should be.  There are a lot of 
details hidden from you when you evaluate a function call in R.  These 
details are not hidden from you when you evaluate an R function call in C.

You must create an SEXP of the function call with the correct number of 
arguments, populate the argument list with pointers to the actual values 
of the arguments, eval the function call, and extract the values from 
the resulting SEXP.  Of course you need to remember to PROTECT and 
UNPROTECT the function call and the result when working with them.

In most cases there is another intermediate step in that you pass a 
character vector containing the name of the function through .Call and 
you must do the equivalent of the R function call get("My.R.function") 
inside your C code so that you can create the function call.

If you really think that you want to embark on this you could find some 
examples in $(R-SRC)/src/library/stats/src/nls.c

If you know that the R function call is eventually going to call another 
C function it is often easier to short-circuit the process and call the 
other C function directly from within your C code.

More information about the R-devel mailing list