[R] .C, .Fortran and DUP

Thomas Lumley thomas at biostat.washington.edu
Fri Jul 7 17:46:23 CEST 2000

On Fri, 7 Jul 2000, gb wrote:

> In an  R  function, I have a huge matrix  x, which I update
> several times. For some reasons I want to do the updating
> with a call to  .Fortran  (simpler than  .C  with matrices,
> it seems). This is my (simplified) code:
> In the  R  function:
> --------------------
>    ...
>    x <- matrix(0, nrow = n.row, ncol = n.col)
>    storage.mode(x) <- "double"
>    for (i in reps)
>    {
>       stuff <- ...
>       .Fortran("updatex",
>                as.double(stuff),
>                as.integer(n.row),
>                as.integer(n.col),
>                x,
>                DUP = FALSE)
>    }
>    x 
> }       
> The FORTRAN side:
> -----------------
>       subroutine updatex(stuff, nrow, ncol, x)
>       implicit none
>       integer nrow, ncol             
>       double precision stuff(ncol), x(nrow, ncol)
>       (...updating x...)
> --------------------------------------------------
> I use  DUP = FALSE  to avoid copying the huge matrix  x,
> but if I read  ?.C  correctly, this is *dangerous* 
> because of the repeated calls to  .Fortran.
> However, it works fine for me (so far).
> Question: *Is* this dangerous? I have the option of writing
> the whole loop in Fortran, of course, but I want to avoid that
> if possible.

It looks as though this case is safe.  There are two ways in which
DUP=FALSE can be dangerous. 

One is when you trigger garbage collection, which moves x out from under
where Fortran thinks it is. In .Fortran you're probably not calling any R
routines (and if you were you would probably know). 

The second is when you change the value of a variable that is currently
aliased to another variable.  This is a hypothetical problem -- I don't
know that it can happen, but I don't know that it can't.  For example, a
function formal argument might still be stored as reference to the actual
argument, in which case you could change the actual argument as well. This
doesn't happen in your example since you don't change anything except x.

The reason for the warning is that either of these problems could cause
bugs that are very difficult to reproduce, and so to fix. DUP=FALSE is an
optimisation that doesn't preserve the same behaviour as unoptimised code,
so it should be used only when you know that a) the speed matters and
b) your particular code works.


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