Skip to content
Prev 11186 / 12125 Next

[R-pkg-devel] [External] Re: Replacement for SETLENGTH

You may be over-complicating this. Taking mcmc_new in src/lm_lcmc.c
from https://github.com/merliseclyde/BAS, to minimize code changes I
would arrange the memory management along these lines:

SEXP mcmc_new(...)
{
     /* ... */

     /* create and protect ANS */
     SEXP ANS = PROTECT(allocVector(VECSXP, 16));

     /* create the work vectors; placing them in ANS protects them */
     SEXP modelspace = allocVector(VECSXP, nModels);
     SET_VECTOR_ELT(ANS, 1, modelspace);
     SEXP logmarg = allocVector(REALSXP, nModels);
     SET_VECTOR_ELT(ANS, 2, logmarg);
     SEXP modelprobs = allocVector(REALSXP, nModels);
     SET_VECTOR_ELT(ANS, 3, modelprobs);
     /* etc */

     /* do your computations */

     if (nUnique < nModels) {
 	/* new values are protected via ANS;
 	   old ones are immediately available for GC */
 	SET_VECTOR_ELT(ANS, 1, xlengthgets(modelspace, nUnique));
 	SET_VECTOR_ELT(ANS, 2, xlengthgets(logmarg, nUnique));
 	SET_VECTOR_ELT(ANS, 3, xlengthgets(modelprobs, nUnique));
 	/* etc */
     }

     /* ... */
     UNPROTECT(1); /* ANS */
     return ANS;
}

Best,

luke
On Wed, 15 Jan 2025, Merlise Clyde, Ph.D. wrote: