Skip to content

R_GlobalEnv

1 message · James Wettenhall

#
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 *****
[1] 5
[1] 5
Then Rgui crashes!