External data from own matrix

I am trying to take responsibility for supporting Eigen::Matrix memory without copying memory. The data() method retains ownership. The only way I figured out how to do this is by swapping the displayed array:

 Matrix<float, Dynamic, Dynamic, RowMajor> mat = m1 * m2; // want ownership of mat float* float* data = mat.data(); // get the pointer new (&mat) Eigen::Map<Matrix3f>(NULL); // swap the mapped array with anything else // do something with data 

It doesn't seem like it is causing a copy under the hood, but I'm not sure. I am also not sure if this is safe.

+5
source share
1 answer

The destruction of memory from the guts of Eigen impolite, not least because you do not know how it was isolated, or what else belongs to the Matrix.

However, there is a Map template that allows you to wrap an uncured buffer in a type similar to a matrix.

This type is not an actual native matrix, so your own custom functions may not work with it, but it should work with Eigen functions.

In this case, you already have the data.

 using matrix_type = Matrix<float, Dynamic, Dynamic, RowMajor>; using mapped_matrix_type = Map<matrix_type>; 

Now we create a buffer, wrap it in mapped_matrix_type and assign:

 auto raw = std::make_unique<float[]>(m1.rows()*m2.cols()); // maybe backwards mapped_matrix_type bob(raw.get(), m1.rows(), m2.cols()); bob = m1*m2; 

raw bob data is in a raw , a unique_ptr owned buffer (which can release() if you need to make it completely unoccupied).

Any raw storage mechanism ( vector , raw new , everything else) can replace the raw location.

Code not verified.

+3
source

Source: https://habr.com/ru/post/1264542/


All Articles