The pointer you feed to XPtr
here is the address of a variable that is local to writeMemObject
. Quite naturally you have undefined behavior.
Also, external pointers are typically used for things that are not R objects, and a NumericMatrix
is an R object, so that looks wrong.
If however, for some reason you really want an external pointer to a NumericMatrix
then you could 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 ;
}
So the pointer created by new
outlives the scope of the writeMemObject
function.
Also, please see the changes in getMemObject
, in your version you had:
XPtr<NumericMatrix> out(ptr);
return wrap(out);
You are not dereferencing the pointer, wrap
would just be an identity and return the external pointer rather than the pointee I guess you were looking for.