Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling c++ routines in Matlab [closed]

Tags:

c++

matlab

mex

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?

like image 490
SaraDean Avatar asked Jan 12 '23 16:01

SaraDean


2 Answers

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.

like image 149
Lokesh A. R. Avatar answered Jan 16 '23 01:01

Lokesh A. R.


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.

like image 37
user2485710 Avatar answered Jan 16 '23 02:01

user2485710