rlbond
rlbond

Reputation: 67847

Call C++ code from 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.

Upvotes: 14

Views: 16670

Answers (4)

Marc Lubecke
Marc Lubecke

Reputation: 19

STL is definitely supported. Boost probably yet. The point is as long you have your STL and BOOST deployed on your computer, you should be good to go.

Upvotes: 1

rcs
rcs

Reputation: 68849

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.

Upvotes: 8

David Johnstone
David Johnstone

Reputation: 24470

The C++ files are actually compiled by an external compiler. Use mex -setup to select which one (here is a list of supported compilers). Therefore, you shouldn't have too many weird things happen, nor should you be too restricted by what you can do.

I did some MEX stuff last year, and my memory is a bit rusty, but you do need to construct MATLAB arrays using MEX functions. I found the MATLAB documentation adequate, and the whole experience not too painful.

Upvotes: 1

Edric
Edric

Reputation: 25160

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>).

Upvotes: 3

Related Questions