[Rd] Getting hold of a package's environment from C code

Duncan Murdoch murdoch at stats.uwo.ca
Sun Oct 22 22:28:06 CEST 2006


On 10/22/2006 3:56 PM, Deepayan Sarkar wrote:
> Hi,
> 
> I have a package where I'm calling an R function (say "foo") from C
> code. "foo" is in the same package, but is not exported. I construct
> the call using lang1(install("foo")), but to eval it I need the
> package's environment.  Is there a way to do this? Passing the correct
> environment through .Call() is not an option.
> 
> Right now, I'm getting the environment first using something like
> 
>   rho = PROTECT(eval(lang2(install("environment"), install("bar")),
> R_GlobalEnv))
> 
> where bar _is_ exported. However, this doesn't work if the package is
> loaded but not attached, and is also risky because someone might
> define another "bar" that is found first.

In R code, you could use getNamespace("pkg") to get the namespace 
environment.  I haven't tried this, but I'd assume

PROTECT(rho = eval(lang2(install("getNamespace"),
                          ScalarString(mkChar("pkg"))));

(or something like it) would be the C equivalent.

 >
 > One solution that might work is to make 'rho' a global variable and
 > assign the correct value when the package is loaded. Is that a good
 > idea? How should I PROTECT it?

I'd say to avoid globals if you can, and I think you can here.

Duncan Murdoch




More information about the R-devel mailing list