<div dir="ltr"><div><div><div>I have a question similar to a previous question I asked here regarding the passing of XPtr objects between functions (<a href="https://www.mail-archive.com/rcpp-devel@lists.r-forge.r-project.org/msg08389.html">https://www.mail-archive.com/rcpp-devel@lists.r-forge.r-project.org/msg08389.html</a>).  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.<br><br></div><div>Thoughts???<br><br><br></div><div>R code<br><br></div><div>library(Rcpp)<br></div><div>sourceCpp("test.cpp")<br><br></div><div>A <- matrix(rnorm(10), 5)<br><br></div><div># This works<br></div><div>testFloatReturn(testArmaFloatXptr(A), 5, 2)<br><br></div><div># This does not<br></div><div>testFloatReturn(testEigenFloatXptr(A), 5, 2)<br></div><div><br></div>C++ Code<br><br>#include <RcppArmadillo.h><br>#include <RcppEigen.h><br><br>using Eigen::Matrix;<br>using Eigen::Dynamic;<br>using Eigen::Map;<br>using Eigen::MatrixXf;<br><br>template<class T><br>using MapMat = Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> >;<br><br>using namespace Rcpp;<br><br><br>// [[Rcpp::export]]<br>SEXP testArmaFloatXptr(arma::fmat A)<br>{<br>    MapMat<float> *B = new MapMat<float>(A.memptr(), (int) A.n_rows, (int) A.n_cols);<br>    XPtr<MapMat<float> > pMat(B);<br>    return(pMat);<br>}<br><br>// [[Rcpp::export]]<br>SEXP testEigenFloatXptr(Eigen::MatrixXf A)<br>{<br>    MapMat<float> *B = new MapMat<float>(&A(0), A.rows(), A.cols());<br>    XPtr<MapMat<float> > pMat(B);<br>    return(pMat);<br>}<br><br>// [[Rcpp::export]]<br>void testFloatReturn(XPtr<MapMat<float> > ptrA, int nr, int nc)<br>{<br>    MapMat<float> A = *ptrA;<br>    cout << A << std::endl;<br>}<br><br><br></div>Regards,<br></div>Charles<br></div>