简体   繁体   English

如何从Eigen :: Matrix获取内存所有权?

[英]How to acquire memory ownership from Eigen::Matrix?

A dynamically sized Eigen::Matrix holds its values in a continuous memory block. 动态大小的Eigen::Matrix将其值保存在连续的内存块中。 I need these values as a memory block I own. 我需要这些值作为我拥有的内存块。 I currently copy the values over using std::memcpy . 我目前使用std::memcpy复制值。

#include <cstdlib>
#include <cstring>
#include <eigen3/Eigen/Core>
using RowMajorMatrixXf = Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;
int main()
{
    RowMajorMatrixXf mat(1024, 2048);
    // ...
    const std::size_t num_bytes = mat.rows() * mat.cols() * sizeof(float);
    float* ptr = (float*)std::malloc(num_bytes); // raw ptr for simplicity
    std::memcpy(ptr, mat.data(), num_bytes);
    // ...
    std::free(ptr);
}

However the copying is unnecessary, since the Eigen::Matrix is no longer needed at this point. 但是复制是不必要的,因为此时不再需要Eigen::Matrix How can I acquire the ownership of the memory of the Eigen Matrix, essentially preventing the Matrix object from freeing the memory in its destructor? 我如何获取本征矩阵的内存所有权,从而本质上防止Matrix对象释放其析构函数中的内存?

You can better allocate your own buffer, and interpret as an Eigen's matrix using Map : 您可以更好地分配自己的缓冲区,并使用Map解释为本征矩阵:

float* ptr = new float[r*c];
Map<RowMajorMatrixXf> mat(ptr,r,c);

and then use mat just like RowMajorMatrixXf, except its true type is not a RowMajorMatrixXf, so you cannot pass it by reference to a function taking a RowMajorMatrixXf& , for that use Ref<RowMajorMatrixXf> or Ref<const RowMajorMatrixXf> . 然后像RowMajorMatrixXf一样使用mat,除了它的真实类型不是RowMajorMatrixXf之外,因此您不能通过引用将其传递给采用RowMajorMatrixXf&的函数,因为该函数使用Ref<RowMajorMatrixXf>Ref<const RowMajorMatrixXf>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM