Create a MATLAB MEX file for a C program

百般思念 提交于 2019-12-02 08:35:28

问题


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 dozen files in a folder, including one called main.c that processes inputs from the command line passes the results to other classes that do the actual calculations.

Normally, to install this program from the command line, I would run ./configure, make at the UNIX command prompt. Then, to run the program, ./runMyProgram -f input_file.txt -p some_parameters. The program takes a text file consisting of a list of numbers as input and prints a table of results in the command window. I want to feed the program a MATLAB array (instead of a .txt file) and get back an array (instead of a printed table of results).

I have read the MEX documentation from The Mathworks (which I found rather opaque), as well as some other "tutorials", but I am totally lost - the examples are for very simple, single-file C programs and don't really discuss how to handle a larger and more complicated program. Is it enough to replace the main.c file with a MEX file that does the same things? Also, how do I compile the whole package within MATLAB?

I would be grateful for any plain-English advice on where to start with this, or pointers to any tutorials that deal with the subject in a comprehensible way.


回答1:


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
}


来源:https://stackoverflow.com/questions/15883018/create-a-matlab-mex-file-for-a-c-program

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!