c++ - 将现有内存映射到 Matlab mxArray 而不会浪费内存

标签 c++ matlab pointers memory mex

我正在为 Matlab 处理一个巨大的矩阵(超过 20.000x20.000 double )的文件。我想在完成计算后,将作为本征矩阵处理的结果矩阵映射到 mxArray,而无需内存复制和在内存上分配其他空间。

Eigen::MatrixXd myfunction(const Eigen::MatrixXd &W)
{
    return W*2;
}

void mexFunction( int nOutputArgs, mxArray *outputArgs[], int nInputArgs, const mxArray * inputArgs[])
{   
    int M = mxGetM(inputArgs[0]);
    int N = mxGetN(inputArgs[0]);

    // Create the input matrix W as Eigen Matrix mapping the input matrix
    Eigen::Map<Eigen::MatrixXd> W( mxGetPr(inputArgs[0]) ,M,N);

    // Allocate space for the output matrix G
    Eigen::MatrixXd G = myfunction(W);

    double *Gdata = G.data();
    outputArgs[0] = mxCreateDoubleMatrix(M,N,mxREAL);
    memcpy(mxGetPr(outputArgs[0]), Gdata, sizeof(double)*M*N);

    return;
}

我问是否可以将指向 plhs[0] 的指针与矩阵 G 的指针对齐(在 Eigen 中作为 G.data() ) 还是我需要执行 memcpy

最佳答案

这可能有效(未经测试,未准备好 matlab):

outputArgs[0] = mxCreateDoubleMatrix(0,0,mxREAL);
mxSetM(outputArgs[0], M);
mxSetN(outputArgs[0], N);
mxSetPr(outputArgs[0], Gdata);

首先创建一个空矩阵可以防止 matlab 分配一堆您实际上不需要的内存。

虽然这可能有效,但要注意:

您必须确保 Eigen::MatrixXd 不会在 mexFunction 返回后自行删除此内存块,这很可能是怎么回事即将发生。这会让您再次回到 memcpy

关于c++ - 将现有内存映射到 Matlab mxArray 而不会浪费内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21700897/

相关文章:

c - 两道C题

c++ - 为什么我的外部变量还没有初始化?

arrays - 更快地搜索大型数组 matlab

matlab - 如果图像使用 matlab,则区域周围的最小矩形边界框

c++ - 指针可以指向一个值,指针值可以指向地址吗?

c - 通过指针给变量赋值

c++ - 微软XML。获取数据为 Base64

c++ - C++中 bool 类型的奇怪行为

C++ 对象指针静态列表和内存泄漏

matlab - 插值 matlab 颜色图