Passing Eigen::Map<ArrayXd> to a function expecting ArrayXd&

喜夏-厌秋 提交于 2019-12-25 02:03:26

问题


Some of my Eigen C++ methods need to be callable from plain C++, therefore I want to provide overloaded functions that accept c arrays and map them to ArrayXd using Eigen::Map.

The code I currently have looks like this:

bool Dmp::executeStep(double* position, double* velocity,
                  double* acceleration, const int len)
{
  Map<ArrayXd> posMap(position, len);
  Map<ArrayXd> velMap(velocity, len);
  Map<ArrayXd> accMap(acceleration, len);
  return executeStep(posMap, velMap, accMap);
}


bool Dmp::executeStep(ArrayXd& position, ArrayXd& velocity, ArrayXd& acceleration)
{
//Code that modifies position, velocity and acceleration
}

This does not work because there is no known conversation from Map<ArrayXd> to ArrayXd&. What is the correct way of doing this?

edit: The answer that luk32 pointed out below would work, however it involves moving my code to the header file which is something I would like to avoid if at all possible.


回答1:


You should make the executeStep a template function. Or use their other facilities like Ref There is a whole comprehensive tutorial in docs on Writing Functions Taking Eigen Types as Parameters.

I am not sure if Map has a more direct parent than EigenBase (maybe Dense really not sure), but as it is most general it should work:

template <typename Derived>
void Dmp::executeStep(EigenBase<Derived>& pos,EigenBase<Derived>& vel, EigenBase<Derived>& acc )
{
// fun ...
}

Of course you need to declare it as a template member too.

I really highly suggest reading the whole tutorial.

Using Ref implementation. I am not sure however if there is a copy from Map to MyMatrix made. Ref do not accept Map objects as it seems to cast them to DenseMatrix.

#include <Eigen/Core>
#include <iostream>

using namespace Eigen;

typedef Matrix<int,2,4>  MyMatrix ;

void print_size(const Ref<const MyMatrix>& b)
{
  std::cout << "size (rows, cols): " << b.size() << " (" << b.rows()
            << ", " << b.cols() << ")" << "\n";
}

int main()
{
  int array[8];
  for(int i = 0; i < 8; ++i) array[i] = i;
  Map<MyMatrix> map(array);
  std::cout << "Column-major:\n" <<  map << "\n";
  print_size(map);
}



回答2:


This is exactly the purpose of the Ref<> class:

bool Dmp::executeStep(Ref<ArrayXd> position, Ref<ArrayXd> velocity, Ref<ArrayXd> acceleration)
{
}


来源:https://stackoverflow.com/questions/22193538/passing-eigenmaparrayxd-to-a-function-expecting-arrayxd

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!