Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call C++ code from MATLAB?

Tags:

c++

matlab

I have some code which I need to code in C++ due to heavy reliance on templates. I want to call this code from MATLAB: basically, I need to pass some parameters to the C++ code, and have the C++ code return a matrix to MATLAB. I have heard this is possible with something called a MEX file which I am still looking into. However I am not sure what is supported in these MEX files. Is all of C++ (e.g. STL and Boost) supported? How difficult is it?

EDIT: I don't need any shared libraries, just header-only stuff like shared_ptr.

like image 405
rlbond Avatar asked Oct 21 '09 16:10

rlbond


People also ask

How do you call C in MATLAB?

From within your MATLAB® code, you can directly call external C/C++ code, also called custom code or legacy code. To call C/C++ functions, use coder. ceval . The code generator integrates your C/C++ code into the C/C++ code generated from MATLAB.

Can we convert MATLAB code to C?

To convert MATLAB® Code to fixed-point C Code using the MATLAB Coder™ app: Open the MATLAB Coder app. On the Select Source Files page, add the entry-point function from which you want to generate code. Set Numeric Conversion to Convert to fixed point .

Can Simulink generate C code?

Simulink® Coder™ generates standalone C and C++ code from Simulink models for deployment in a wide variety of applications. For a list of DSP System Toolbox™ features supported by Simulink Coder, see Blocks Supported for C Code Generation.


2 Answers

Have a look at the MEX-files Guide, especially Section 25–27 for C++. The basic STL/Boost data structures should work, but threading with Boost could be a problem.
cout will not work as expected in C++, mexPrintf has to be used instead.

like image 82
rcs Avatar answered Oct 05 '22 11:10

rcs


It's certainly possible to write C++ MEX files which use STL and boost. In general, you should be able to do anything you please inside a C++ MEX file. The main practical restriction is that MATLAB already ships with a bunch of libraries, so if you're using one of the boost pieces that needs a shared library (some are header-only), you'll need to match the version you compile against with that shipping with MATLAB.

For instance, MATLAB R2009b ships with boost 1.36 (you can tell by looking at the names of the libraries in <matlabroot>/bin/<arch>).

like image 22
Edric Avatar answered Oct 05 '22 10:10

Edric