Create an Eigen Matrix from a C array

There is little chance that Eigen::Matrix will ever be allowed to directly wrap external buffers, and there are many good reasons for that including ABI compatibility, API consistency across dynamically and statically allocated matrices.

An ugly workaround would be to define a struct with the same layout as MatrixX_:

template<typename T> struct Foo {
  T* data;
  DenseIndex rows, cols;
  Matrix<T, Dynamic, Dynamic, ColMajor>& asMatrix() {
    return reinterpret_cast<Matrix<T, Dynamic, Dynamic, ColMajor>&>(*this);
  }
};

Another solution would be to move to the devel branch (pretty stable), and use the new Ref<> class that was designed to solve your exact problem, and more. Its documentation should be enough to use it properly. The only difficulty is that you be able to easily templatize the scalar type because Ref<> is not a base class of Matrix or Map, and so you will have to either call your fonction by specifying the scalar type explicitly, or create the Ref<> copy yourself:

foo<T>(M);
foo(Ref<MatrixXd>(M));

Tags:

C++

Arrays

Eigen