[Rcpp-devel] Passing XPtr of Eigen Map object between functions

Charles Determan cdetermanjr at gmail.com
Fri Jun 26 14:43:29 CEST 2015


I have tried a few more feeble attempts (explicitly create pointer to pass,
passing just the MatrixXf object) at getting the Eigen object to persist
between functions without the additional Armadillo wrapper but with no
success.  Anyone have any additional thoughts?

Many thanks,
Charles

On Thu, Jun 25, 2015 at 10:34 AM, Charles Determan <cdetermanjr at gmail.com>
wrote:

> I have a question similar to a previous question I asked here regarding
> the passing of XPtr objects between functions (
> https://www.mail-archive.com/rcpp-devel@lists.r-forge.r-project.org/msg08389.html).
> Exploring the same topic with the Eigen library I have run in to another
> curious situation.  As per the previous suggestion I was under the
> impression that I need to create a `new` object which I then wrap in an
> XPtr to be passed between functions.  However, this becomes a problem when
> trying to work with RcppEigen.  I try to pass in a matrix as MatrixXf to be
> mapped but the resulting output shows some numbers matching and others
> completely wrong.  This is likely me not understanding how Eigen objects
> are handled in memory but I am confused in that if I pass the matrix in as
> an arma::fmat object which I then Map to an Eigen MatrixXf it works without
> issue.
>
> Thoughts???
>
>
> R code
>
> library(Rcpp)
> sourceCpp("test.cpp")
>
> A <- matrix(rnorm(10), 5)
>
> # This works
> testFloatReturn(testArmaFloatXptr(A), 5, 2)
>
> # This does not
> testFloatReturn(testEigenFloatXptr(A), 5, 2)
>
> C++ Code
>
> #include <RcppArmadillo.h>
> #include <RcppEigen.h>
>
> using Eigen::Matrix;
> using Eigen::Dynamic;
> using Eigen::Map;
> using Eigen::MatrixXf;
>
> template<class T>
> using MapMat = Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>
> >;
>
> using namespace Rcpp;
>
>
> // [[Rcpp::export]]
> SEXP testArmaFloatXptr(arma::fmat A)
> {
>     MapMat<float> *B = new MapMat<float>(A.memptr(), (int) A.n_rows, (int)
> A.n_cols);
>     XPtr<MapMat<float> > pMat(B);
>     return(pMat);
> }
>
> // [[Rcpp::export]]
> SEXP testEigenFloatXptr(Eigen::MatrixXf A)
> {
>     MapMat<float> *B = new MapMat<float>(&A(0), A.rows(), A.cols());
>     XPtr<MapMat<float> > pMat(B);
>     return(pMat);
> }
>
> // [[Rcpp::export]]
> void testFloatReturn(XPtr<MapMat<float> > ptrA, int nr, int nc)
> {
>     MapMat<float> A = *ptrA;
>     cout << A << std::endl;
> }
>
>
> Regards,
> Charles
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20150626/95c1a629/attachment.html>


More information about the Rcpp-devel mailing list