I want to call an R function of my package from an Rcpp function. Both R and Rcpp functions are part of the package rminizinc.
Currently, I am using the approach shown below:
void fun(){
Environment rmzn_env("package:rminizinc");
Function retModel = rmzn_env["getRModel"];
retModel(some_object);
}
But, this approach only works when I export the getRModel()
function. Is there any way I could call getRModel()
without exporting it as I want it to be a helper function which should not be exposed to the user?
You have to get a bit meta here. It is possible to get an environment containing all the unexported functions in a package using the base R function asNamespace
. This function itself can be used inside Rcpp. You then create a new Environment
from the output of that function, from which you can harvest the unexported function.
As an example, let's get the unexported function ggplot2:::as_lower_ascii
to do some work on a string we pass to an Rcpp function:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
CharacterVector fun(CharacterVector input){
Function asNamespace("asNamespace");
Environment ggplot_env = asNamespace("ggplot2");
Function to_lower_ascii = ggplot_env["to_lower_ascii"];
return to_lower_ascii(input);
}
So if we source this, then back in R we can do:
fun("HELLO WORLD")
#> [1] "hello world"