Create a MATLAB MEX file for a C program

后端 未结 1 960
Happy的楠姐
Happy的楠姐 2021-01-24 13:34

I\'m an experienced MATLAB user but totally new to C and MEX files. I have a complex program written in C that I need to call from within MATLAB. The program consists of a few

1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-24 14:29

    Yes. Normally replacing a main.c file with MEX file is the process. In your case since you already have complex build setup, it might be easier to build a library and then build a separate mex file which just links against this library. This will be much easier than building the whole thing using mex command. If you export the function you need to call from your library, you can call it from your mexFunction. mexFunction can do all the creation and reading of mxArrays. A simple sample mexFunction can be,

    #include "mex.h"
    // Include headers for your library
    
    void
    mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])
    {
       void* x = mxGetData(prhs[0]); // Assume one input. Check nrhs
       plhs[0] = mxCreateDoubleMatrix(10,10,mxREAL); // Create 10x10 double matrix for output
       void* y = mxGetData(plhs[0]);
       yourLibraryFunction(x, y); // Read from x and write to y. Pass sizes in if needed
    }
    

    0 讨论(0)
提交回复
热议问题