[R] when .Call can safely modify its arguments

Prof Brian Ripley ripley at stats.ox.ac.uk
Sat Feb 28 10:49:43 CET 2004


On Sat, 28 Feb 2004, Vadim Ogranovich wrote:

> Hi,
>  
> "Writing R Extensions Guide" clearly states that a C-function interfaced
> via .Call() should not modify any of its arguments. However I wonder if
> there are exceptions to this rule, i.e. when .Call can safely modify the
> arguments. For example when a function creates a list that is then
> populated by a call to a C function:
>  
> getData <- function() {
>     data <- list(a=double(2), b=character(3))
>  
>     # now populate_list modifies data
>     .Call("populate_list", data) 
>  
>     data
> }
>  
>  
> What can go wrong in this example?

I don't think anything can, but there is no advantage over using

data <- .Call("populate_list", data)

which makes the intention much clearer.

We would rather you didn't name objects the same as R system functions, 
though.

> And while we are here I wonder what happens to 'data' when getData()
> returns it. Is it copied or some more efficient mechanism is used?

Nothing.  If the call to getData is of the form

foo <- getData()
bar <- foo

then foo and bar are still the same object, but if either is subsequently 
changed (at R level) it will be copied before being changed.


The way to understand internal details like this is to study the current
source code.  They do change from time to time, and we do find errors from 
time to time.

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