From simon.urbanek at r-project.org  Thu Oct  1 18:51:19 2009
From: simon.urbanek at r-project.org (Simon Urbanek)
Date: Thu, 1 Oct 2009 12:51:19 -0400
Subject: [Rd] creating environments in package's C code
In-Reply-To: <4AC4DAC8.6010107@vanderbilt.edu>
References: <4AC4CBD9.7010309@mx.uni-saarland.de>
	<4AC4D3C5.7090609@vanderbilt.edu> <4AC4DAC8.6010107@vanderbilt.edu>
Message-ID: <E04283F5-2542-4FE5-B7EE-A9D1F691C0B4@r-project.org>

Jeff,

On Oct 1, 2009, at 12:37 , Jeff Horner wrote:

> Jeff Horner wrote:
>> 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;
>> }
>

eek ... that some dangerous bit of code ;). I think Rf_NewEnviroment  
is safer even if it's not the headers :P.


> Oops! I forgot the definition of my simple function NewInteger:
>
> static SEXP NewInteger(int i){
>    SEXP val;
>    PROTECT(val = NEW_INTEGER(1));
>    INTEGER_DATA(val)[0] = i;
>    UNPROTECT(1);
>    return val;
> }

I suspect you like reinventing the wheel ;). Your NewInteger is part  
of the R API and is called ScalarInteger(). When you need something,  
chances are that R has it already, so it's worth greping through the  
headers (and sometimes even through the main sources).

Cheers,
Simon



>
>> 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
>> ______________________________________________
>> R-devel at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-devel
>
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
>
>



[Rd] creating environments in package's C code
Simon Urbanek