Remove input R object in C++ function environment -
i have rcpp function inside r function. r function produces object (say large list) , feeds rcpp function. inside rcpp function, copy r object's data number of c++ classes, , on r object practically useless. want release memory r object (or maybe mark garbage if deleting hard?).
the idea is:
// [[rcpp::export]] void cppfun(list structureddata) { // copy structureddata c++ classes // want structureddata gone save memory // main algorithms ... } /***r rfun(input) { # r creates structureddata input cppfun(structureddata) } */
i tried calling r's "rm()" in c++ can identify object names in r's global environment. example:
// [[rcpp::export]] void cppfun() { language("rm", "globaldat").eval(); language("gc").eval(); } /***r globaldat = 1:10 ls() # shows "globaldat" created. cppfun() # shows "globaldat" no longer in environment. ls() */
however, following not work:
// [[rcpp::export]] void cppfun() { language("rm", "localdat").eval(); language("gc").eval(); } /***r rfun <- function (x) { locdat = x ls() // shows "x" , "locdat" created cppfun() ls() } globaldat = 1:10 ls() # shows "globaldat" created. rfun(globaldat) # print "x","locdat" twice , warning message: in rm("localdat") : object 'localdat' not found locdat = globaldat rfun(globaldat) # still remove "locdat" global environment. */
am on right track goal? there better way?
thank you!
thought of hacky way 64-bit machine. more convenient methods still welcome.
write shell class wraps necessary c++ structured data classes.
in r function, process input --> feed structured r data rcpp function --> in rcpp function, new shell class object, load structured r data shell class object's members --> memcpy shell class pointer double (8 byte) --> return double --> return double out of r function. structured r data dies while newed c++ shell object still lives. call gc() try memory release.
feed double main c++/rcpp function. make pointer shell class using memcpy. code algorithms. delete shell class pointer before function returns.
tests show above works. found there exists "external pointer" or rcpp::xptr designed similar purposes.
doing along these lines known antipattern, or highly counterproductive, in rcpp. why problematic rcpp performs shallow copy when moving r object c++, means r object shares it's memory allocation instantiated c++ object. if remove r object while c++ object references it, may run trouble later in process segmentation fault (segfault) occur.
now, if intend deep copy r object c++ structure, wouldn't quite toxic. when doing deep copies, data not reference original r object. however, not default schema rcpp.
with being said, strongly discourage deleting objects mid-process. if memory strapped, try "chunking"/dividing data more, perform operations database, buy additional ram, or wait altrep
.
Comments
Post a Comment