[R-pkg-devel] Call internal R functions in C

Duncan Murdoch murdoch@dunc@n @end|ng |rom gm@||@com
Mon Apr 26 11:30:48 CEST 2021

On 25/04/2021 10:30 p.m., Cai Li wrote:
> Thanks Duncan! I was advised not to export those functions in the 
> namespace and keep them as internals. In terms of this, could you advise 
> what specific changes should I make to the C code so that I can evaluate 
> them in a suitable environment? I tried something like 
> "PROTECT(func_R=lang2(install("Package:::R_function"), func_data))," but 
> it did not work. Sorry this may be too naive and thanks again.

That line creates the expression to evaluate, it doesn't evaluate it. 
You need to call eval() (the C function) on the result.  Here's some 
code from rgl that does something similar:

R code to initialize:

rgl.init <- function(initValue = 0, onlyNULL = FALSE, debug = 
getOption("rgl.debug", FALSE))
   .Call( rgl_init,
     initValue, onlyNULL, environment(rgl.init), debug )

The important thing here is "environment(rgl.init)", which is the 
private environment within the package.

Then in C code, save that environment:

   rglNamespace = in_namespace;

and use it later:

   result = eval(PROTECT(lang2(PROTECT(install("rglFonts")),
PROTECT(ScalarString(mkChar(family))))), rglNamespace);

Duncan Murdoch

> Cai
> On Sun, Apr 25, 2021 at 8:46 PM Duncan Murdoch <murdoch.duncan using gmail.com 
> <mailto:murdoch.duncan using gmail.com>> wrote:
>     On 25/04/2021 7:23 p.m., Cai Li wrote:
>      > Hello All,
>      >
>      > I'm developing a package with C code. My question may be naive: I
>     have
>      > several internal R functions that need to be called by C, but I
>     cannot get
>      > it to work or find a solution. It can work if I export those internal
>      > functions in namespace, but it fails if I just want to keep them as
>      > internal functions without exporting them. I guess I need some
>     flags to
>      > indicate the "internal" R internal functions? Could you please
>     share your
>      > thoughts on how to fix this? Much appreciated in advance!
>      >
>      > //   set up call to R function "R_function"
>      >      SEXP func_R;
>      >      PROTECT(func_R=lang2(install("R_function"), func_data));
>      >
>     It all depends on the environment where you evaluate that expression,
>     just as it would if it was R code.  You can't see internal package
>     functions from the global environment, you need to evaluate them in the
>     package namespace environment.
>     Duncan Murdoch

More information about the R-package-devel mailing list