tags:

views:

302

answers:

3

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.

+2  A: 

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.

rcs
I will provide some caution from experience. If you use Simulink and RTW, when compiling the flag -DRT is set. Some of boost's math libs use template<class RT>. The -DRT kills these classes. If you run into this issue, try changing -DRT to -DRT=RT in the make file.
KitsuneYMG
A: 

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

Edric
A: 

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.

David Johnstone