[Rcpp-devel] Passing XPtr between functions

Charles Determan cdetermanjr at gmail.com
Tue Jun 23 21:25:37 CEST 2015


I am exploring the use of some XPtr objects.  For example, I can create a
pointer to an armadillo matrix.  I can then create a copy of that matrix
from the pointer within the same function.  However, when I try to pass a
pointer to a function and create a new copy from said pointer it fails
(returns matrix of ~zeros).  I feel like I am missing something obvious.
Below you will find my code.

Regards,
Charles

test.R
library(Rcpp)
sourceCpp("test.cpp")

A <- matrix(rnorm(10), 5)

# This returns correctly
testPtr(A)

# passing a Xptr in to the function returns matrix of ~zeros.
testReturn(testXptr(A), 5, 2)


test.cpp
#include <RcppArmadillo.h>

using namespace Rcpp;

// [[Rcpp::export]]
void testPtr(SEXP data){
    arma::mat A = as<arma::mat>(data);
    int nr = A.n_rows;
    int nc = A.n_cols;

    Rcpp::XPtr<double> ptrA(A.memptr());

    arma::mat B = arma::mat( ptrA,
          nr,
          nc,
          true);
    B.print("copied matrix");
}

// [[Rcpp::export]]
SEXP testXptr(SEXP A)
{
    arma::Mat<double> armaMat = Rcpp::as<arma::Mat<double> >(A);
    Rcpp::XPtr<double> pMat(armaMat.memptr());
    return(pMat);
}

// [[Rcpp::export]]
void testReturn(XPtr<double> ptrA, int nr, int nc)
{
    arma::Mat<double> B = arma::Mat<double>( ptrA,
          nr,
          nc,
          true);
    B.print("copied matrix");
}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20150623/31723d65/attachment.html>


More information about the Rcpp-devel mailing list