I've got a long code in C++ and I want to call it from MATLAB.
I read that, using MEX-files, calling large pre-existing C/C++ and Fortran routines from MATLAB without rewriting them as MATLAB functions is possible.
However, MEX files are cumbersome and apparently one should change the whole code. Furthermore, I have problems in calling the C/C++ compiler from MATLAB's command line. In particular, MATLAB asks
Select a compiler:
[1] Lcc-win32 C 2.4.1 in D:\PROGRA~1\MATLAB\R2013a\sys\lcc
[2] Microsoft Visual C++ 2010 in D:\Program Files\Microsoft Visual Studio 10.0
but my code is written in Borland c++ but MATLAB could not recognize Borland as a compiler.
Is there any way, simpler than what I'm currently doing, to integrate C/C++ codes in MATLAB by MEX-files?
As mentioned by user2485710, you should use the MEX interface to call your existing C++ code. MEX interface is basically a wrapper around your existing C++ code.
For example, if your called is call add.c, which adds two numbers, you will not be able to call it directly in MATLAB. Your wrapper should look like this,
#include "mex.h"
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[]) { // Standard gateway function
double *a = mxGetPr(prhs[0]);
double *b = mxGetPr(prhs[1]);
double c = add(a,b);
mxSetPr(plhs[0], &c);
}
This is a illustrative example, you might have to read the documentation for the each of the functions I have used. You need not worry about the compiler. Most C++ programs work in all compilers. Choose one of the compilers in your list and work with it. There are some limitations, but I do not know of anyone who hit this usecase.
reading from here , it's clear that Matlab can be interfaced with C or Fortran; now how do you go from C++ to C ? You use extern "C"
.
Read here for a quick intro on the subject, but basically it's all you have to do, put an extern
to expose C interfaces for your C++ functions so both the linker and the compiler know how to correctly build a C interface.
The FAQ also discuss some limitations of this solution because of the different features offered by C++ and C.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With