[R] problem when I Call C subfunction in void function

Thomas Lumley tlumley at uw.edu
Thu Aug 28 03:21:46 CEST 2014


On Thu, Aug 28, 2014 at 3:36 AM, eguichard <elie.guichard at inserm.fr> wrote:
> Thank you.
> I can improve my program with your response but I have an other problem.
>
> /double essai (double *Px, int *tailleP)
> {
>         int i;
>         for (i = 0; i < *tailleP; i++)
>         {
>                 Px[i]=Px[i]*2;
>                 Rprintf ("I print Px %f\t", Px[i]);
>         }
>         Rprintf("\n");
>         return *Px;
> }

*Px is a single double, the same as Px[0]

>
> void test_essai (double *Px, int *tailleP, double *res)
> {
>         int i;
>         *res = essai(Px, tailleP);

This is more clearly written as
          res[0] = essai(Px, tailleP);

It sets the first element of res to the double returned by essai()

If you want essai() to modify all the elements of the array that res
points to, you need to pass res to the function.

>         for (i = 0; i < *tailleP; i++)
>         {
>                 Rprintf ("I print res %f\t", res[i]);
>         }
> }/
>
> When I compile it in R
> /trajPx <- c(2,5,5,4)
> .C("test_essai",Px = as.numeric(trajPx),tailleP =
> as.integer(length(trajPx)),res = numeric(4))/
>
> I have the following result:
>
> I print Px 4.000000     I print Px 10.000000    I print Px 10.000000    I
> print Px 8.000000
> I print res 4.000000    I print res 0.000000    I print res 0.000000    I
> print res 0.000000
>  $Px
> [1]  4 10 10  8
>
> $tailleP
> [1] 4
>
> $res
> [1] 4 0 0 0
>
> I haven't problem in "essai" function but I can't correctly return "Px"
> vector.
> I d'ont understand why I get only the first number (number 4 in my exemple)
> ?
>
>



-- 
Thomas Lumley
Professor of Biostatistics
University of Auckland



More information about the R-help mailing list