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.
Romain francois
source share