Skip to content

dynamic array output by .C

6 messages · Tib, Simon Urbanek, Brian Ripley

Tib
#
Greetings,

I am building a stochastic simulation model in a C++ shared library
for R. My model will generate a random number of new observations and
also delete some old observations, however, the numbers cannot be
predicted before the computation engine runs. For simplicity, I am
trying to control my programming at the second stage (pure C++ for R).
It seems .C accepts fixed size of arrays as input (also ouput), can I
modify size of array for deleting old and adding new observations in
.C?
Thanks in advance.
#
On Thu, 14 Apr 2005, Tib wrote:

            
No, but .Call can.
Tib
#
HI,
from the examples of Writing R Extensions,  I see one still has to
declare the size of arrays by NEW_NUMERIC(n) or
allocVector(REALSXP,n), how can I extend arrays?

I know this question is a little specific, but it would be a lot
helpful if anyone can give me a  quick question. Thanks
On 4/14/05, Prof Brian Ripley <ripley@stats.ox.ac.uk> wrote:

  
    
#
On Apr 14, 2005, at 6:01 PM, Tib wrote:

            
AFAIR you cannot extend vectors - it's like in C, you cannot extend  
allocated memory without changing the pointer (i.g.). In order to get  
a vector of a different size, you have to allocate a new one and copy  
the common contents. If you are concerned about efficiency, why don't  
you just use arbitrary large vectors and pass along the number of  
used elements? Then you can easily add elements without re-allocating  
and just return the number of elements used after the operation. That  
way you can control the probability of having to allocate a new  
vector, possibly making it zero.

Cheers,
Simon
#
On Thu, 14 Apr 2005, Tib wrote:

            
Use lengthgets().

  
    
#
On Thu, 14 Apr 2005, Simon Urbanek wrote:

            
That's not a particularly good idea, as R keeps the length in the vector.
There is a way to do this, lengthgets().  That shortens vectors in one 
case, and reallocates and copies contents if extending.  Quite a lot of 
internal code does use long vectors and call lengthgets() at the end to 
shorten them to the right size.  (Other code duplicates that in 
lengthgets.)

As the name implies, this is the internal form of length(x) <- value.

Yes, it does change the pointer because it creates (potentially a new 
object).  But since an R object is just a few parameters (e.g. type and 
length) and a pointer, you could in fact extend an R vector `in place'.