Search code examples
c++arrayspointersconstantsarmadillo

Armadillo C++ - Initialize read-only matrix from const memory without copying


A very good answer to how to create an Armadillo matrix around existing memory is given here: armadillo C++: matrix initialization from array.

I have a situation however where I would like to create an Armadillo matrix from a const array, without copying the data first. The first part is easy:

  • mat(const aux_mem*, n_rows, n_cols)

Create a matrix by copying data from read-only auxiliary memory.

However this copies the memory first, which would be unnecessary in my case.

I would like to have something like this:

const double* ptr = start; // I cannot modify the source of this pointer

const amra::mat M(ptr, 4, 4, /*copy*/ false, /*strict*/ true); 

However this exact constructor does not exist. Is there an alternative method that I'm missing?


Solution

  • Use const_cast to remove the const qualifier from the pointer.

    In your case this is const arma::mat M(const_cast<double*>(ptr), 4, 4, false, true);