store and retrieve matrices in memory using xptr

与世无争的帅哥 提交于 2019-12-05 03:48:05

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.

What you describe it pretty much the use case for the bigmemory package. Michael Kane wrote a nice Rcpp Gallery article about its use with Rcpp which should address your questions.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!