[R] Problem with length of array while calling C from R

Martin Maechler maechler at stat.math.ethz.ch
Tue Apr 24 15:30:29 CEST 2007

>>>>> "Sven" == Sven Knüppel <sven.knueppel at reilich.net>
>>>>>     on Tue, 24 Apr 2007 13:53:09 +0200 writes:

    Sven> Hello,
    Sven> my problem is that I don't know how long must be an array of double while calling C from R.

    Sven> R-Code:
    >> array <- c(1,1,1)
    >> save <- .C ( "Ctest" , a = array )

    Sven> C-Code: void Ctest ( double *array ) { ...  array =
    Sven> (double*) realloc ( array , new_number *
    Sven> sizeof(double) ) ; ...  }

    Sven> The length of "array" will be compute in C.

    Sven> At the end save$a has a length of 3 and not the length of the allocated array in C.

    Sven> What can I do?

Either you learn to use  .Call()  where you pass whole R
objects, and can use  length(.) on them in your C code,

or, simpler in this case, but much less powerful in general,
you change your R code to

   ss <- .C("Ctest", a = myarray, n = length(myarray))

and the C code to

    void Ctest (double *array, int *n) { 

and then make use of  *n  inside the C code.

Martin Maechler, ETH Zurich

More information about the R-help mailing list