[Rd] Huge matrices in .Call

Hin-Tak Leung hin-tak.leung at cimr.cam.ac.uk
Thu Aug 24 19:51:16 CEST 2006


Dominick Samperi wrote:
> I assume that the fact that SEXP's passed through .Call
> are read-only is a convention, consistent with R semantics.
> 
> This can be awkward when huge matrices are passed
> as in:
> newP <- .Call("myfunc", P)
> because this would cause the huge matrix to be copied.

Yes, I think that's the practice - basically what you want
is in-place modification of objects, which is contrary to
what most R people would recommend.

> Is there any danger if I violate the convention in cases
> like this and modify the SEXP matrix parameter directly,
> instead of forcing R to make a copy of it every time
> myfunc is called? (This seems to work in my testing.)

Prof. Ripley is probably going to say something about this...
but I think as long as (1) you tell the garbage collector
about you going to mess around with the input with
PROTECT() (this is probably automatic for input to .Call()
so may not be necessary), (2) you are doing exact in-place
changes, no resizing, no messing around the attributes,
no relocations elsewhere, etc, then nobody needs to get upset
about you messing around with the internal of a matrix, so to speak,
and technically it should work, *although doing so is very much
frown upon*.

In which case, if I were writing this, I would get myfunc() to
return logical(TRUE/FALSE) to indicate success/failure or some
more detail operation status. return'ing SEXP *input is probably
dangerous and will probably confuse the garbage collector. I don't know
for sure, but I would avoid it. so I would write it as:

status <- .Call("myfunc", P)
if (status) {
    cat("Ha, I have got a new P!\n")
    print(P)
} else {
    cat("things don't work out and P is probably very broken\n")
    print(P)
}

(somebody will yell at me on coroborating this, but I have uses
for in-place modification of big objects too...)

HTL



More information about the R-devel mailing list