I have an Rcpp function inside an R function. The R function produces some object (say a large list) and feeds it to the Rcpp function. Inside the Rcpp function, I process the R object, load the results to a number of C++ classes. Now the R object becomes useless. I want to wipe out the R object to make a memory-sufficient environment for the main algorithms.
The idea is:
// [[Rcpp::export]]
void cppFun(List structuredData)
{
// copy structuredData to C++ classes
// Now I want structuredData gone to save memory
// main algorithms ...
}
/***R
rFun(input)
{
# R creates structuredData from input
cppFun(structuredData)
}
*/
I tried calling R's "rm()" in C++ but it can only identify the object names in R's global environment. For example:
// [[Rcpp::export]]
void cppFun()
{
Language("rm", "globalDat").eval();
Language("gc").eval();
}
/***R
globalDat = 1:10
ls() # shows "globalDat" is created.
cppFun() # shows "globalDat" is no longer in the environment.
ls()
*/
However, the following does not work:
// [[Rcpp::export]]
void cppFun()
{
Language("rm", "localDat").eval();
Language("gc").eval();
}
/***R
rFun <- function (x)
{
locDat = x
ls() // shows "x" and "locDat" are created
cppFun()
ls()
}
globalDat = 1:10
ls() # shows "globalDat" is created.
rFun(globalDat) # it will print "x","locDat" twice and a warning message: In rm("localDat") : object 'localDat' not found
locDat = globalDat
rFun(globalDat) # this will still remove "locDat" from the global environment.
*/
Am I on the right track to the goal? Is there any better way?
Thank you!
Thought of a hacky solution:
Write a shell class wrapping references to all the necessary C++ structured data classes.
In the R function, (i) process the input; (ii) feed the structured R data to the Rcpp function; (iii) in the Rcpp function,
newa shell class object, load the structured R data; (iv)memcpythe shell class pointer to adouble(8 bytes, if 32-bit system, useint); (v) return thedouble; (vi) return thedoubleout of the R function. Now the structured R object dies while thenewed C++ shell object still lives. Callgc()for garbage collection.Feed the
doubleto the main C++/Rcpp function.memcpythis double to a shell class pointer.deletethe shell class pointer before function returns.
Tests show the above works. Just found "external pointer" or Rcpp::XPtr designed for a similar purpose?