matlab in C C++ and C C++ in matlab

Tim picture Tim · Oct 16, 2009 · Viewed 11.8k times · Source

It seems that are several ways to call matlab in C C++ and to call C C++ in matlab. While I try to list them here, please point it out If I miss something.

To call C C++ in matlab, there are also two methods. The first one is to call functions in C shared libraries. The second one is to build C C++ code into binary MEX-files, which will be called from the MATLAB command line. For the first method, are the C shared libraries are just general ones, i.e. without change to their C code for matlab and compiled from general C compiler like gcc?

To call matlab code in C C++, there are two methods available. The first one is Matlab engine. The second one is to use MATLAB Compiler mcc to create C or C++ shared libraries from your MATLAB code.

Besides matlab and C C++ can communicate via writing and reading data to and from some file (e.g. mat file, text file).

Having more than one ways to accomplish each of the goals here, could you tell me what cases are best for using which of them? i.e. calling functions in C shared libraries VS building C C++ code into binary MEX-files, Matlab engine VS compiling Matlab code into C C++ shared library.

Thanks and regards!

Answer

Jason B picture Jason B · Oct 16, 2009

I only have expreience with calling C or C++ functions from MATLAB. It looks to me like the only difference between calling functions in a shared library and calling functions from a MEX file is that with a shared library, you have to call the function with 'calllib' which is a command line type function and MEX functions allow you to call functions as if they are built-in functions so the interface is a little cleaner.

My suggestion is to use MEX files if

  • You are using C++ (you may have to write a wrapper to use a C++ in a shared library)
  • You are using MATLAB as the glue for a large number of optimized C or C++ routines. You'll want to be able to call them cleanly.

Use shared library if

  • You already have an existing C library that can be used without modification.
  • You only need a small number of calls to C functions.

Really, it comes down to the interface. I personally prefer the MEX file route because it provides the cleanest interface from MATLAB to your C or C++ function. You can call it like just another function with standard MATLAB types. With a shared library, you may have to do some data formatting before calling the library function