From therneau at mayo.edu  Mon Apr  1 20:54:58 2013
From: therneau at mayo.edu (Terry Therneau)
Date: Mon, 01 Apr 2013 13:54:58 -0500
Subject: [Rd] Timing of SET_VECTOR_ELT
In-Reply-To: <B88959A2-D5E3-4580-9094-CA98FAF9ECA0@r-project.org>
References: <5159BF6E.5050709@mayo.edu>
	<B88959A2-D5E3-4580-9094-CA98FAF9ECA0@r-project.org>
Message-ID: <5159D802.6000706@mayo.edu>



On 04/01/2013 12:44 PM, Simon Urbanek wrote:
> On Apr 1, 2013, at 1:10 PM, Terry Therneau wrote:
>
>> Assume a C program invoked by .Call, that returns a list.
>>
>> Near the top of the program we allocate space for all the list elements. (It is my habit to use "xyz2" for the name of the R object and "xyz" for the pointer to its contents.)
>>
>>     PROTECT(means2 = allocVector(REALSXP, nvar));
>>     means = REAL(means2);
>>     PROTECT(u2 = allocVector(REALSXP, nvar));
>>     u = REAL(u2);
>>     PROTECT(loglik2 = allocVector(REALSXP, 2));
>>     loglik = REAL(loglik2);
>>
>>     PROTECT(rlist = mknamed(VECSXP, outnames));
>>
>> Can I assign the individual elements into rlist using SET_VECTOR_ELT at this point, or do I need to wait until the end of the program, after I've filled in means[i], u[i], etc.?  I likely depends on whether I'm assigning a pointer or a copy.
>>
> You're assigning a pointer, so it doesn't matter.
>
> FWIW, you can avoid all the PROTECTion mess if you alloc+assign, e.g.
>
> SEXP rlist = PROTECT(mknamed(VECSXP, outnames));
> SEXP means = SET_VECTOR_ELT(rlist, 0, allocVector(REALSXP, nvar));
> ...
>
> since you only need to protect the parent object.
>
> Cheers,
> Simon
Neat trick.  I take it that SET_VECTOR_ELT returns a pointer to the object that was just 
created?  I haven't found a description of the function in any of the documents, only 
examples of its use, so this is a surprise to me.
    Lacking documentation, can I count on it in the future?

Terry T.



[Rd] Timing of SET_VECTOR_ELT
Terry Therneau