[R] using the .C interface to call compiled C code

Prof Brian D Ripley ripley at stats.ox.ac.uk
Fri Feb 23 08:37:42 CET 2001


On Fri, 23 Feb 2001, Faheem Mitha wrote:

> Dear People,
>
> I have been trying to learn how to use the .C interface. A friend gave me
> a toy example, and I have been playing with it. It is
>
>
> (C code)
>
> #ifdef USING_R
>   typedef int Sint;
> #else
>   typedef long Sint;
> #endif
>
> void kosum(double *a, double *b, Sint *na)
> {
>   int i, j, nab;
>   double temp;
>   nab=*na;
>   temp=0.0;
>   for(i=0;i < nab; i++)
>   {
>     temp=temp+a[i];
>   }
>    *b=temp;
> }
>
>
> And the calling code in R is
>
> test1<-
> function(a, b)
> {
>         .C("kosum",
>                 as.double(a),
>                 b = double(1),
>                 as.integer(length(a)))[[2]]
> }
>
> Now, I noticed that if I change
>
> for(i=0;i < nab; i++) to say for(i=0;i <= nab; i++) or even
> for(i=0;i <= nab + 1; i++)
>
> everything seems happy, and I get the same answers. But I don't understand
> why this is so. I am surely trying to read from nonexistent memory in this
> case, and I should have some problems.

The memory exists.  It is not allocated as part of your R object a.  It
happened to contain 0 on the system you tried this on, on the occasion on
which you tried it.   Reading outside arrays can give wrong answers, and
writing outside them can cause other calculations to give wrong answers or
even crash R.

It is important to write correct C.  Using your compiler's checking tools
(lint, -Wall, ...) will help.  But in this case the C code has no
indication of how large the array pointed to by `*a' is, so it is down to
the programmer to check that the two sides of the R/C interface are
consistent.

> I may be missing the obvious, but I am neither very experienced in R or in
> C.
>
> Also, if anyone has a simple example of using .C that they would like to
> share with me, or if they can point to me to (very) simple examples in the
> source code that would be suitable for an beginner, I would be extremely
> grateful.

`Writing R Extensions' has the official R examples.  There are many, many
more in packages, both shipped with R and on CRAN.  Look in
src/library/eda/src and src/library/mva/src for some really simple ones.

-- 
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 272860 (secr)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list