使用xptr在内存中存储和检索矩阵 [英] store and retrieve matrices in memory using xptr
问题描述
我希望能够在内存中存储在R中创建的矩阵并返回指针.然后,稍后使用指针从内存中取回矩阵.我正在Ubuntu 3.01和Rcpp版本"0.10.6"上运行R版本3.0.1(2013-05-16)-"Good Sport".我已经尝试过...
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". 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))
但是这失败了,当我再次尝试时会崩溃R
But this fails and crashes R when I try again
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
只是一个标识并返回外部指针,而不是我猜您正在寻找的指针.
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屋!