Calling C ++ routines in Matlab

I have a long C ++ code 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 all the code needs to be changed. Also, I am having problems calling the C / C ++ compiler from the MATLAB 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 doing now to integrate C / C ++ codes into MATLAB using MEX files?

+4
source share
3 answers

As already mentioned by user 2485710, you must use the MEX interface to call your existing C ++ code. The MEX interface is basically a wrapper for your existing C ++ code.

For example, if your called call calls add.c , which adds two numbers, you cannot call it directly in MATLAB. Your cover 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 an illustrative example; you may have to read the documentation for each of the functions that I used. You do not need to worry about the compiler. Most C ++ programs work in all compilers. Select one of the compilers in your list and work with it. There are some limitations, but I do not know anyone who got into this usecase.

+6
source

after reading here , it is clear that Matlab can be paired with C or Fortran; now how do you switch from c ++ to c? You are using extern "C" .

Read here for quick topic entry, but basically all you have to do is put extern to display the C interfaces for your C ++ functions, therefore both the linker and the compiler know how to build the C interface correctly.

Frequently asked questions also discuss some of the limitations of this solution due to the various possibilities offered by C ++ and C.

+2
source

As an alternative to creating a real Matlab interface using MEX files, you can also simply call your C ++ program using system calls . First you have to write down the data necessary for the files first, which is inefficient, but probably better than writing a true interface if you do not plan to use it often.

+1
source

Source: https://habr.com/ru/post/1495923/


All Articles