The first thing is the compiler. In Windows, you can only choose a specific compiler, say, C/C++ or Fortran. So if you work with both C and Fortran code, you will have to use "mex -setup" from time to time, which is kinda annoying for a lazy person like me. But in Linux, you can work on a configuration file so that Matlab will automatically select the compiler for you.
First, in "/opt/R2009a/unix/bin/mexopts.sh", you can see the following segment:
#
FC='g95'
FFLAGS='-fexceptions'
FFLAGS="$FFLAGS -fPIC -fno-omit-frame-pointer"
FLIBS="$RPATH $MLIBS -lm"
FOPTIMFLAGS='-O'
FDEBUGFLAGS='-g'
#
The first line indicates the compiler for Fortran. "g95" is not provided, so, we will change it to gfortran which I think comes with Ubuntu. Thus, change this segement into:
#
FC='gfortran'
FFLAGS='-fexceptions'
FFLAGS="$FFLAGS -fPIC -fno-omit-frame-pointer"
FLIBS="$RPATH $MLIBS -lm"
FOPTIMFLAGS='-O'
FDEBUGFLAGS='-g'
#
Then, in Matlab, if you type
mex -setup
You will see something like:
The options files available for mex are:
1: /opt/R2009a/unix/bin/gccopts.sh :
Template Options file for building gcc MEX-files
2: /opt/R2009a/unix/bin/mexopts.sh :
Template Options file for building MEX-files via the system ANSI compiler
Choose 2. Then it's ok to compile.
The next thing is the interface. The help in Matlab has everything you know to create a wrapper, even some examples for you to follow. So although I know nothing about Fortran, I managed to write a "almost" complete interface which passed the compilation.
However, there're several important tips that costs me a whole day to figure out.
- The name of the source file must be ".F", otherwise it won't compile.
- If the source code you want to wrap was not developed by you, be very careful about all the data types in that code. For example, if one input for that function is "REAL", then it is 4-byte floating number. And in Matlab, unless specified, everything will be "double", which is 8-byte floating number. If you pass the double value directly into it, the value will NOT be preserved. So when you call the function in Matlab, use something like "nlam = int32(nlam);
beta = single(beta);" Also, inside the interface, use something like "mxCopyPtrToReal4(beta_pr,beta,size)". - The next thing is managing the output. When you create the output matrices, do not use mxCreateDoubleMatrix. Use "mxCreateNumericMatrix", which will let you to specify the output types like int32 or single.