使用xptr存储和检索存储器中的矩阵 [英] store and retreive matrices in memory using xptr
问题描述
我想能够将在R中创建的矩阵存储在内存中并返回指针。然后稍后使用指针从内存中取回矩阵。我运行R版本3.0.1(2013-05-16) - 好运动在Ubuntu 13.01和Rcpp版本0.10.6。谢谢。我试过...
I would like to be able to store a matrix created in R in memory and return the pointer. And then later use the pointer to fetch back the matrix from memory. I am running R version 3.0.1 (2013-05-16) -- "Good Sport" on Ubuntu 13.01 and Rcpp version "0.10.6". Thanks. I have 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))
getMemObject(x)
Error: not compatible with REALSXP
推荐答案
您输入 XPtr
这里是 writeMemObject
的本地变量的地址。很自然,你有未定义的行为。
The pointer you feed to XPtr
here is the address of a variable that is local to writeMemObject
. Quite naturally you have undefined behavior.
此外,外部指针通常用于不是R对象的事物,并且 NumericMatrix
是R对象,所以看起来错了。
Also, external pointers are typically used for things that are not R objects, and a NumericMatrix
is an R object, so that looks wrong.
但是,如果由于某种原因,你真的想要一个外部指针 NumericMatrix
,那么你可以这样做:
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 ;
}
因此,由 new
超出了 writeMemObject
函数的作用域。
So the pointer created by new
outlives the scope of the writeMemObject
function.
此外,请在您的版本中查看 getMemObject
中的更改:
Also, please see the changes in getMemObject
, in your version you had:
XPtr<NumericMatrix> out(ptr);
return wrap(out);
您不能取消引用指针 wrap
只是一个身份,并返回外部指针,而不是pointee,我猜你在寻找。
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.
这篇关于使用xptr存储和检索存储器中的矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!