如何将结构从Matlab代码转换为C代码(使用Matlab编译器)

时间:2015-01-15 20:02:48

标签: c matlab structure matlab-deployment matlab-compiler

我一直在尝试使用Matlab编译器创建一个C共享库,该编译器现在将作为插件库用于不同的应用程序。我最近以为我已经完成了这个任务,只是为了意识到我从新的" Matlab Compiled"共享库需要将其返回转换为C结构。

我使用Matlab Answers网站上的示例来帮助我创建包装器level2函数来调用我需要返回结构的Matlab函数。(http://www.mathworks.com/matlabcentral/answers/94715-how-do-i-wrap-matlab-compiler-4-8-r2008a-created-c-dlls-to-create-another-dll

我的问题是在下面找到的代码将返回的MATLAB数据转换为C数据部分。我可以很好地转换为int,double,chars等,但是我无法弄清楚如何编译从matlab返回的mxArray到C结构的转换。

/* Wrapper for level 1 function exported by the MATLAB generated DLL         *
 * This function converts C data to MATLAB data, calls the MATLAB generated  *
 * function in level1.dll and then converts the MATLAB data back into C data */

int wmlfLevel1(double* input2D, int size, char* message, double** output2d){
    int nargout=1;

    /* Pointers to MATLAB data */
    mxArray *msg;
    mxArray *in2d;
    mxArray *out2d=NULL;

    /* Start MCR, load library if not done already */
    int returnval=isMCRrunning();
    if(!returnval)
        return returnval;

    /* Convert C data to MATLAB data */
    /* IMPORTANT: this has to be done after ensuring that the MCR is running */
    msg=mxCreateString(message);
    in2d=mxCreateDoubleMatrix(size, size, mxREAL);
    memcpy(mxGetPr(in2d), input2D, size*size*sizeof(double));

    /* Call the M function */
    returnval=mlfLevel1(nargout, &out2d, in2d, msg);

    /*Convert returned  MATLAB data to C data */
    *output2d=(double *)malloc(sizeof(double)*size*size);
    memcpy(*output2d, mxGetPr(out2d), size*size*sizeof(double));

    /* Clean up MATLAB variables */
    mxDestroyArray(msg);
    mxDestroyArray(in2d);
    mxDestroyArray(out2d);

    return returnval;
}

到目前为止,我已尝试使用mxCreateStructMatrix函数,我尝试创建一个C结构框架,我即将尝试使用libstruct函数,但由于我是C编程和Matlab编译器的新手,所以非常感谢任何帮助!< / p>

1 个答案:

答案 0 :(得分:1)

mxGetPr只是返回一个指向双精度缓冲区的指针。 malloc调用正在分配足够的空间来存储大小^ 2的双倍。 memcpy正在将数据从out2d的内部存储中复制到缓冲区中。

缓冲区是一维的,因此您必须根据行和列计算索引。您可以使用output2d[col * size + row]之类的内容来访问特定值。 (这可能会转换 - 我现在无法访问文档。)

当您完全使用output2d时,您需要调用free(output2d)来释放内存,否则您的代码会有内存泄漏。

相关问题