Store and retrieve matrices in memory using xptr

I would like to be able to store the matrix created in R in memory and return a pointer. And then later use the pointer to return the matrix from memory. I am launching R version 3.0.1 (2013-05-16) - "Good Sport" on Ubuntu 13.01 and Rcpp version "0.10.6". I tried...

// [[Rcpp::export]] SEXP writeMemObject(NumericMatrix mat) { XPtr<NumericMatrix> ptr(&mat, true); return ptr; } // [[Rcpp::export]] NumericMatrix getMemObject(SEXP ptr) { XPtr<NumericMatrix> out(ptr); return wrap(out); } # This returns a pointer x <- writeMemObject(matrix(1.0)) 

But it will fail and R will crash when I try again

 getMemObject(x) Error: not compatible with REALSXP 
+7
c ++ reference matrix r rcpp
source share
2 answers

The pointer you pass to XPtr here is the address of a variable that is local to writeMemObject . Naturally, you have undefined behavior.

In addition, external pointers are commonly used for things that are not R objects, and NumericMatrix is an R object, so this does not look right.

If, however, for some reason you really need an external pointer to NumericMatrix , then you can do something like this:

 #include <Rcpp.h> using namespace Rcpp ; // [[Rcpp::export]] SEXP writeMemObject(NumericMatrix mat){ XPtr<NumericMatrix> ptr( new NumericMatrix(mat), true); return ptr; } // [[Rcpp::export]] NumericMatrix getMemObject(SEXP ptr){ XPtr<NumericMatrix> out(ptr); return *out ; } 

Thus, the pointer created by new highlights the scope of the writeMemObject function.

Also, see the changes to getMemObject in your version:

 XPtr<NumericMatrix> out(ptr); return wrap(out); 

You are not looking for a pointer, wrap will just be the identifier and will return the external pointer, not the pointer that I think you were looking for.

+4
source share

What you described to a large extent for use in the bigmemory package. Michael Kane wrote about its use with Rcpp, which should have solved your issues.

+2
source share

All Articles