[R] correct C function usage

Prof Brian Ripley ripley at stats.ox.ac.uk
Tue Dec 13 22:35:29 CET 2005


On Tue, 13 Dec 2005, Ido M. Tamir wrote:

> Hello,
> I am not sure if I am interfacing with C correctly and _safely_
> or if there is a better way esp. with regards to terminating
> the "returned" array.

You need to pass the length to the C routine and check you do not 
overwrite it.  (As in the parts you -snip-ed below.)

> I am trying to fill an int array with values whose actual size
> is determined in the C function and is always maximally as large
> as length(values).
>
> I also don't understand the purpose of $ab in the example:
> conv <- function(a, b)
>       .C("convolve",
>      -snip-
>          ab = double(length(a) + length(b) - 1))$ab

.C returns a list, an element for each argument after the first, named if 
the arguments were named.  So this selects the (copy) of the vector sent 
back as the last argument of the C function.

> void testFill(int *values, int *newvalues, int* endposition ){
>         newvalues[0] = 1;
>         newvalues[1] = 2;
>         *endposition = 2;
> }
>
> dyn.load("../testFill.so")
>
> testTestFill <- function(){
>  tempfilled <- testFillC( c(30:40))
>  realfilled <- tempfilled$newvalues[1:tempfilled$endposition]
>  return(realfilled)
> }
>
> testFillC <- function(a){
>  .C("testFill", as.integer(a), newvalues=integer(length(a)),
> endposition=integer(1))
> }

What do testFillC(1) or testFillC(logical(0)) do?

-- 
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