[R] R_GlobalEnv

James Wettenhall wettenhall at wehi.edu.au
Wed May 28 04:14:21 CEST 2003


Hi,

I'm trying to access the current R global environment from 
within C, using R_GlobalEnv.

In the example below, Rgui (R 1.7.0. Win2K) crashes when I try 
to run assignValueToFooInR_GlobalEnv, but not when I run 
assignValueToFooInRhoEnv with Rho=.GlobalEnv.  Can anyone tell me why?

[ My motivation is that I want use defineVar to initialise a 
workingEnvironment (corresponding to Value below), so that event-handler 
functions for a specific C library (which must have a specific 
prototype) can call R functions by looking up workingEnvironment with 
findVar. Earlier, I tried a static global SEXP variable in C to 
keep track of the environment, but that's not reliable because 
of garbage collection. Maybe SEXPREC would work better? ]

Thanks in advance,
James


***** testR_GlobalEnv.c *****
#include <R.h>
#include <Rinternals.h>
#include <R_ext/Rdynload.h>
#include <R_ext/Memory.h>
#include <R_ext/Applic.h>

static SEXP assignValueToFooInRhoEnv(SEXP Value,SEXP Rho)
{
    defineVar(install("Foo"),Value,Rho);
    return Value;
}

static SEXP assignValueToFooInR_GlobalEnv(SEXP Value)
{
    defineVar(install("Foo"),Value,R_GlobalEnv);
    return Value;
}

static const
R_CallMethodDef CallEntries[] = {
{"assignValueToFooInRhoEnv",     
(DL_FUNC)&assignValueToFooInRhoEnv,2},
{"assignValueToFooInR_GlobalEnv", 
(DL_FUNC)&assignValueToFooInR_GlobalEnv,1},
{NULL,NULL,0}
};

void R_init_testR_GlobalEnv(DllInfo *info)
{
  R_registerRoutines(info,NULL,CallEntries,NULL,NULL);
}


***** In R *****
> dyn.load("testR_GlobalEnv")
> .Call("assignValueToFooInRhoEnv", 5, .GlobalEnv)
[1] 5
> Foo
[1] 5
> .Call("assignValueToFooInR_GlobalEnv", 5)

Then Rgui crashes!




More information about the R-help mailing list