[Rcpp-devel] Passing XPtr between functions

Hadley Wickham h.wickham at gmail.com
Wed Jun 24 21:22:39 CEST 2015


On Wed, Jun 24, 2015 at 11:08 AM, Charles Determan
<cdetermanjr at gmail.com> wrote:
> Many thanks Krzysztof, your suggestion works.  I can explicitly create a
> 'new' arma::mat object and pass the resulting XPtr between functions.  I
> will work on making everything prettier and document for a submission to
> Rcpp Gallery unless someone is aware of one that already exists that I
> somehow overlooked.
>
> // [[Rcpp::export]]
> SEXP testXptr(NumericMatrix A)
> {
>     arma::mat *armaMat = new arma::mat(A.begin(),A.rows(), A.cols(), false);
>     XPtr<arma::mat> pMat(armaMat);
>     return(pMat);
> }
>
> // [[Rcpp::export]]
> void testReturn(SEXP ptrA, int nr, int nc)
> {
>     XPtr<arma::mat> ptrB(ptrA);
>     arma::mat B = arma::mat( (double *) ptrB->memptr(),
>           nr,
>           nc,
>           false);
>     B.print("copied matrix");
> }

You can make this a little nicer:

// [[Rcpp::export]]
void testReturn(XPtr<arma::mat> ptrA, int nr, int nc)
{
    arma::mat B = arma::mat( (double *) ptrA->memptr(),
          nr,
          nc,
          false);
    B.print("copied matrix");
}

Hadley

-- 
http://had.co.nz/


More information about the Rcpp-devel mailing list