From jeff.horner at vanderbilt.edu  Thu Oct  1 18:07:33 2009
From: jeff.horner at vanderbilt.edu (Jeff Horner)
Date: Thu, 01 Oct 2009 11:07:33 -0500
Subject: [Rd] creating environments in package's C code
In-Reply-To: <4AC4CBD9.7010309@mx.uni-saarland.de>
References: <4AC4CBD9.7010309@mx.uni-saarland.de>
Message-ID: <4AC4D3C5.7090609@vanderbilt.edu>

Martin Becker wrote:
> Dear developers,
> 
> is it possible to create environments in C code of packages?
> Simply using
>  SEXP env;
>  PROTECT (env  = allocSExp(ENVSXP));
> and assigning the enclosing environment with SET_ENCLOS seems to be 
> insufficient.
> 
> Best wishes,

Here's a function I use in rapache to create one:

static SEXP NewEnv(SEXP enclos){
     SEXP env;
     PROTECT(env = allocSExp(ENVSXP));

     SET_FRAME(env, R_NilValue);
     SET_ENCLOS(env, (enclos)? enclos: R_GlobalEnv);
     SET_HASHTAB(env, R_NilValue);
     SET_ATTRIB(env, R_NilValue);

     UNPROTECT(1);

     return env;
}


and an example that creates a new environment and then assigns a 
variable named OK an integer vector length 1 with value 0:

SEXP env = NewEnv(R_GlobalEnv);
defineVar(install("OK"),NewInteger(0),env);

Best

Jeff



[Rd] creating environments in package's C code
Jeff Horner